<?php

namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);

use app\admin\Controller;
use think\Db;
use think\Config;
use think\Exception;
use think\Request;
use think\Validate;

set_time_limit(0);

class DispatchTravelerGroup extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    /**
     * 校正司机的状态
     */
    public function revise()
    {
        // 查找派单处于进行中的司机
        $proceedData = Db::name('dispatch_traveler_group')->where('dispatch_group_status', 'proceed')->field('driver_user_id')->select();
        if ($proceedData) {
            foreach ($proceedData as $index => $proceedDatum) {
                $driverStatus = Db::name('driver')->where('user_id', $proceedData['driver_user_id'])->find();
                if ($driverStatus && !$driverStatus['inservice']) {
                    Db::name('driver')->where('user_id', $proceedData['driver_user_id'])->update(['inservice' => 1]);
                }
            }
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index(Request $request)
    {

       $data = input();

//        //搜索
        //订单ID
        if ($this->request->param("order_id")) {
            $map['o.order_id'] = array('like', "%{$this->request->param("order_id")}%");
        }

        //预订人
        if ($data['booking_people_name']) {
            $map['o.booking_people_name'] = array('like', "%{$data['booking_people_name']}%");
        }

        //预订人电话
        if ($data['booking_people_phone']) {
            $map['o.booking_people_phone'] = array('like', "%{$data['booking_people_phone']}%");
        }


        //平台
        if ($data['platform']) {
            $map['o.platform'] = $data['platform'];
        }

        //出行日期
        if ($data['start_time'] && $data['end_time']) {
            $map['o.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        } elseif ($data['start_time']) {
            $map['o.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['start_time'] . " 23:59:59")]);
        } elseif ($data['end_time']) {
            $map['o.start_time'] = array("between", [strtotime($data['end_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        }

        //预订人备注
        if ($data['booking_people_remark']) {
            $map['o.booking_people_remark'] = array('like', "%{$data['booking_people_remark']}%");
        }
        //是否已经预订房间
        if ($data['isbooking']) {
            $map['pt.isbooking'] = 1;
        }
        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");

        $map['o.dispose_status'] = 'vehicle_dispatching';
        $map['ot.group_id'] = 0;
        $map['ot.is_error'] = 0;

        //查询订单信息
        $list = Db::name('order_traveler')
            ->alias("ot")
            ->join("order o", "o.id=ot.oid", 'left')
            ->join("portion_traveler pt", "o.id='pt.oid'", 'left')
            ->where($map)
            ->group('ot.oid')
            ->order('o.id desc')
            ->field("ot.*,o.*,'pt.isbooking'")
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        dump(Db::name('order_traveler')->getLastSql());
        $new_list = $list->toArray()['data'];
        foreach ($new_list as $key => $item) {
            if (empty($item['id'])) {
                unset($new_list[$key]);
            } else {
                $new_list[$key]['order_remark'] = Db::name('order_remark')
                    ->where('order_id', $item['order_id'])
                    ->order('id desc')
                    ->select();
                continue;
            }
        }

        $oids = [];
        $order_travelers = [];
        //整合订单ids
        foreach ($new_list as $item) {

            if ($oids[$item['order_id']] != true) {

                $travelers = $item;
                $arr = Db::name('order_traveler')->where('oid', $item['id'])->field('id')->select();
                $travelers['num'] = count($arr);
                $travelers['show_single'] = true;
                $travelers['show_mian'] = false;
                $travelers['show_between'] = false;
                $travelers['show_end'] = false;
                $travelers['route_title'] = Db::name('route')
                    ->where('id', $item['route_id'])
                    ->value('title');
                //获取该订单的旅客信息
                $travelers_info = Db::name('order_traveler')->where('oid', $item['id'])->select();
                $arr = [];
                foreach ($travelers_info as $k => $v) {
                    $arr[] = $v['id'] . '-' . $v['name'];
                }
                $info = implode(',', $arr);
                $travelers['travelers_info'] = $info;
                $travelers['hotel_accommodations'] = Db::name('hotel_accommodation')
                    ->alias("ha")
                    ->where("'ha.oid'", $item['id'])
                    ->join("hotel h","ha.hotel_id=h.id","left")
                    ->join("hotel_room_type hrt","hrt.id=ha.hotel_room_type","left")
                    ->field("ha.*,h.hotel_name,hrt.room_name")
                    ->select();
                $travelers['travelers_info_list'] = $travelers_info;
                //查询该订单的关联订单id
                $relevance_id = Db::name('order')->where('id', $item['id'])->value('relevance_id');
                //获取订单ids
                $order_ids = Db::name('order_relevance')->where('relevance', $relevance_id)->field('order_id')->select();
                $relevance_order_list = [];
                foreach ($order_ids as $k => $v) {
                    if ($v['order_id'] != $item['id']) {
                        $relevance = Db::name('order')->where('id', $v['order_id'])->find();
                        //获取关联订单的旅客信息
                        $relevance_travelers_info = Db::name('order_traveler')->where('oid', $v['order_id'])->select();
                        $relevance_travelers_info = Db::name('order_traveler')->where('oid', $v['order_id'])->select();
                        $relevance['num'] = count($relevance_travelers_info);
                        $arrs = [];
                        foreach ($relevance_travelers_info as $kt => $vt) {
                            $arrs[] = $vt['id'] . '-' . $vt['name'];
                        }
                        $relevance_info = implode(',', $arrs);
                        $relevance['travelers_info'] = $relevance_info;
                        $relevance['travelers_info_list'] = $relevance_travelers_info;
                        $relevance['order_remark'] = Db::name('order_remark')
                            ->where('order_id', $v['order_id'])
                            ->order('id desc')
                            ->select();
                        $relevance_order_list[] = $relevance;
                    }
                }
                $travelers['relevance_order_list'] = $relevance_order_list;
                $order_travelers[] = $travelers;
                $oids[$item['order_id']] = true;

            }

        }

        // 模板赋值显示
        $platform = Db::name('platform')->select();
        $this->view->assign('Request.param.ctime', $data);
        $this->view->assign('Request.param.start_time', $data);
        $this->view->assign('platform', $platform);
        $this->view->assign('list', $order_travelers);
        if (!empty($order_travelers)) {
            $this->view->assign("count", count($order_travelers));
        }
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());

        if ($request->isAjax()) {
            $this->view->assign('refresh', 1);
            return $this->view->fetch('ajaxpage');
        } else {
            return $this->view->fetch('undistributed_traveller');
        }
    }

    /**
     * 拒单
     * @return mixed
     */
    public function in_reject()
    {

        $data = input();
        if ($data['go_date']) {
            $map['dtg.go_date'] = array("between", [strtotime($data['go_date'] . " 00:00:00"), strtotime($data['go_date'] . " 23:59:59")]);

        }

        if ($data['sales_id']) {
            $map['dtg.sales_id'] = array('in', $data['sales_id']);
        }

        if ($data['dispatch_group_status']) {
            $map['dtg.dispatch_group_status'] = $data['dispatch_group_status'];
        }
        if ($data['car_form']) {
            $map['dtg.car_form'] = array('like', "%{$data['car_form']}%");
        }
        if ($data['remark']) {
            $map['dtg.remark'] = array('like', "%{$data['remark']}%");
        }
        if ($data['is_settlement'] || $data['is_settlement'] === "0") {
            $map['dtg.is_settlement'] = $data['is_settlement'];
        }

        $map['isreject'] = true;
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
        $list = DB('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_admin_user u', 'u.id=dtg.driver_user_id', 'left')
            ->field('dtg.*,u.realname')
            ->where($map)
            ->order("dtg.reject_time desc")
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $this->view->assign('list', $list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 派单中列表
     * 李正
     * @return mixed
     */
    public function in_sendorders()
    {

        $map['dtg.dispatch_group_status'] = 'sendorders';
        $data = input();
        //派车单号
        if ($data['id']) {
            $map['dtg.id'] = array('like', "%{$data['id']}%");
        }
        //客人
        if ($data['grname']) {
            $mapu['name'] = array('like', "%{$data['grname']}%");
            $group_id = Db::name('order_traveler')->where($mapu)->field('group_id')->select();
            if ($group_id) {
                foreach ($group_id as $k => $v) {
                    $dis_id[] = $v['group_id'];
                }
                $map['dtg.id'] = array('in', $dis_id);
            }
        }
        //司机
        if ($data['realname']) {
            $mapa['realname'] = array('like', "%{$data['realname']}%");
            $au = Db::name('admin_user')->where($mapa)->field('id')->select();
            if ($au) {
                foreach ($au as $k => $v) {
                    $au_id[] = $v['id'];
                }
                $map['dtg.driver_user_id'] = array('in', $au_id);
            }
        }
        //出行日期
        if ($data['start_time'] && $data['end_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        } elseif ($data['start_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['start_time'] . " 23:59:59")]);
        } elseif ($data['end_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['end_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        }
        //用车形式
        if ($data['car_form']) {
            $map['dtg.car_form'] = array('=', $data['car_form']);
        }
        $map['isreject'] = false;
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");

        $list = DB('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_dispatch d', 'd.id=dtg.dispatch_id', 'left')
            ->join('tp_driver dr', 'dr.user_id=dtg.driver_user_id', 'left')
            ->field('dtg.num,dtg.is_pickup,dtg.oid as dtg_oid,dtg.route_id,dtg.id,dtg.remark,dtg.dispatch_id,dtg.driver_user_id,dtg.go_date as start_time,dtg.end_date as end_time,dtg.car_form,dr.vehicle_level,dr.driver_rank_id')
            ->where($map)
            ->order("dtg.id desc")
            ->group("d.id")
            ->paginate($listRows, false, ['query' => $this->request->get()]);
//        $list = DB('dispatch_traveler_group')
//            ->alias('dtg')
//            ->join('tp_dispatch_order dor','dor.dispatch_id=dtg.dispatch_id','left')
//            ->join('tp_order or','or.id=dor.oid','left')
//            ->join('tp_driver dr','dr.user_id=dtg.driver_user_id','left')
//            ->field('dtg.num,dtg.is_pickup,dtg.oid as dtg_oid,dtg.route_id,dtg.id,dtg.remark,dtg.dispatch_id,dtg.driver_user_id,dor.oid,dtg.go_date as start_time,dtg.end_date as end_time,dtg.car_form,dr.vehicle_level,dr.driver_rank_id')
//            ->where($map)
//            ->order("dtg.id desc")
//            ->group("dor.dispatch_id")
//            ->paginate($listRows, false, ['query' => $this->request->get()]);
//
//        dump($list);
        $platform = Db::name('platform')->select();
        $this->view->assign('platform', $platform);
        $this->view->assign('list', $list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 更换司机记录
     * 李正
     * @url /admin/dispatch_traveler_group/driver_rejection_write
     */
    public function driver_rejection_write()
    {

        $data = input();

        //派车单号
        if ($data['id']) {
            $map['dispatch_id'] = array('like', "%{$data['id']}%");
        }
        //司机
        if ($data['realname']) {
            $map['realname'] = array('like', "%{$data['realname']}%");
        }
        //客人
        if ($data['grname']) {
            $map['guest_name'] = array('like', "%{$data['grname']}%");
        }
        //出行日期
        if ($data['start_time'] && $data['end_time']) {
            $map['start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        } elseif ($data['start_time']) {
            $map['start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['start_time'] . " 23:59:59")]);
        } elseif ($data['end_time']) {
            $map['start_time'] = array("between", [strtotime($data['end_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        }
        if ($data['car_form']) {
            $map['car_form'] = array('=', $data['car_form']);
        }
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
        if ($data['is_re']) {
            $map['is_rejection'] = array('=', 2);
            $this->view->assign('is_re', 1);
        } else {
            $map['is_rejection'] = array('=', 1);
        }
        $list = DB('driver_rejection_write')
            ->where($map)
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        $platform = Db::name('platform')->select();
        $this->view->assign('platform', $platform);
        $this->view->assign('list', $list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        $this->view->assign('dre', '1');
        return $this->view->fetch();
    }

    /**
     * 更换司机或申请中止
     * 李正
     */
    public function change_driver(Request $request)
    {
        if ($request->isPost()) {
            $editData = $request->post();
//            dump($editData);
//            exit();
            //开启事务
            Db::startTrans();
            //释放司机,同时记录司机的拒单次数
            $driverUser = Db::name('driver')->where('user_id', $editData['driver_user_id'])->find();//司机信息
            //查询该分组的数据
            $group = Db::name('dispatch_traveler_group')->where('id', $editData['id'])->find();
            $status = $group['dispatch_group_status'];

            //恢复分组的状态
            if ($group['dispatch_group_status'] != 'undistributed' || $group['dispatch_group_status'] != 'achieve' || $group['dispatch_group_status'] != 'accounts') {
                //判断是否是中止
                if ($editData['is_rejection'] == 1) {
                    $update['dispatch_group_status'] = 'undistributed';
                }
                $update['driver_confirm'] = false;
                $update['isreject'] = false;
                $update['dispatch_time'] = 0;
                $update['is_settlement'] = false;
                $update['settlement_time'] = 0;
                $update['settlement_time'] = 0;
                $update['driver_user_id'] = 0;
                $update['reset_time'] = NOW_TIME;
                $up = Db::name('dispatch_traveler_group')->where('id', $editData['id'])->update($update);
                if ($group['is_pickup'] == '1') {
                    $upodata['is_pick_up'] = 0;
                    $up = Db::name('order')->where('id', "in",$group['oid'])->update($upodata);
                    if (!$up) {
                        //回滚事务
                        Db::rollback();
                        return ajax_return_adv_error('恢复接机单状态失败!');
                    }
                }
                if (!$up) {
                    //回滚事务
                    Db::rollback();
                    return ajax_return_adv_error('恢复分组状态失败!');
                }
            }
            if (!$driverUser) {
                //回滚事务
                Db::rollback();
                return ajax_return_adv_error('不存在该司机');
            } else {
                //增加司机的拒单次数
                $up = Db::name('driver')->where('id', $driverUser['id'])->where('user_id', $editData['driver_user_id'])->setInc('number_of_refusals', 1);

                //查询该司机在是否还存在派车单
                $dispatchOrder = Db::name('dispatch_traveler_group')
                    ->where('dispatch_group_status', 'in', 'sendorders,proceed')
                    ->where('driver_user_id', $editData['driver_user_id'])
                    ->select();
                if (count($dispatchOrder) == 0) {
                    //如果没有释放该司机
                    Db::name('driver')->where('id', $driverUser['id'])->where('user_id', $editData['driver_user_id'])->update(['inservice' => 0]);
                }

                if (!$up) {
                    //回滚事务
                    Db::rollback();
                    return ajax_return_adv_error('司机增加拒单次数失败!');
                }
            }
            //记录更换司机的原因
            $insert = [
                'dispatch_id' => $group['id'],
                'title' => $editData['title'],
                'dir_price' => $editData['dir_price'],
                'start_time' => $editData['start_time'],
                'end_time' => $editData['end_time'],
                'car_form' => $editData['car_form'],
                'vehicle_level' => $editData['vehicle_level'],
                'realname' => $editData['realname'],
                'remark' => $editData['remark'],
                'dr_rank_name' => $editData['dr_rank_name'],
                'guest_name' => $editData['guest_name'],
                'guest_num' => (int)$editData['guest_num'],
                'rejection_reason' => $editData['rejection_reason'],
                'create_time' => time(),
                'is_rejection' => $editData['is_rejection'],
            ];
            //把更换司机原因添加进表
            $insertGetId = Db::name('driver_rejection_write')->strict(false)->insertGetId($insert);
            //如果是申请中止直接打散
            if ($editData['is_rejection'] == 2) {
                if ($group['is_pickup'] == '1') {//接机单处理
                    //释放司机
                    $dri = Db::name("driver")->strict(false)->where('user_id', $group['driver_user_id'])->update(array('inservice' => 0));

                    // 查找该司机的手机号码
                    $mobile = Db::name('admin_user')->where('id', $group['driver_user_id'])->value('mobile');

                    //更新订单接机分配状态
                    Db::name("order")->strict(false)->where('id', "in",$group['oid'])->update(array('is_pick_up' => 0));
                    //订单旅客回滚为未分配状态
                    $ort = Db::name("order_traveler")->where('group_id', $group['driver_user_id'])->update(array('group_id' => 0));
                    $or = Db::name("order")->where('id',"in", $group['oid'])->update(array('dispose_status' => 'vehicle_dispatching'));

                    //删除派车单相关表数据
                    $dis = Db::name('dispatch')->where('id', $group['dispatch_id'])->delete();
                    $dis_gr = Db::name('dispatch_traveler_group')->where('id', $group['id'])->delete();

                    if (!$dri && !$mobile && !$ort && !$dis && !$dis_gr && !$or) {
                        //回滚事务
                        Db::rollback();
                        return ajax_return_adv_error('中止订单失败');
                    } else {
                        set_info($group['driver_user_id'], '订单分配', "您的订单编号为:{$group['id']}的订单已被取消", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $group['id']));
                        $ret = send_message($mobile, "您的订单编号为:{$group['id']}的订单已被取消");
                        logs('paidan', $ret);
                    }
                } else {//普通单处理
                    //释放司机
                    $dri = Db::name("driver")->strict(false)->where('user_id', $group['driver_user_id'])->update(array('inservice' => 0));

                    // 查找该司机的手机号码
                    $mobile = Db::name('admin_user')->where('id', $group['driver_user_id'])->value('mobile');

                    //订单旅客回滚为未分配状态
                    $ort = Db::name("order_traveler")->where('group_id', $group['driver_user_id'])->update(array('group_id' => 0));
                    //修改所有订单状态
                    $ords = Db::name('dispatch_order')->where('dispatch_id', $group['dispatch_id'])->field('oid')->select();
                    $oids = [];
                    foreach ($ords as $k => $v) {
                        $oids[] = $v['oid'];
                    }
                    $or = Db::name("order")->where('id', 'in', $oids)->update(array('dispose_status' => 'vehicle_dispatching', 'isallot' => 0));
                    //删除派车单相关表数据
                    $dis = Db::name('dispatch')->where('id', $group['dispatch_id'])->delete();
                    $dis_or = Db::name('dispatch_order')->where('dispatch_id', $group['dispatch_id'])->delete();
                    $dis_tr = Db::name('dispatch_traveler')->where('dispatch_id', $group['dispatch_id'])->delete();
                    $dis_gr = Db::name('dispatch_traveler_group')->where('id', $group['id'])->delete();

                    if (!$dri && !$mobile && !$ort && !$dis && !$dis_or && !$dis_tr && !$dis_gr && !$or) {
                        //回滚事务
                        Db::rollback();
                        return ajax_return_adv_error('中止订单失败');
                    } else {
                        set_info($group['driver_user_id'], '订单分配', "您的订单编号为:{$group['id']}的订单已被取消", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $group['id']));
                        $ret = send_message($mobile, "您的订单编号为:{$group['id']}的订单已被取消");
                        logs('paidan', $ret);
                    }
                }
            }
            if (!$insertGetId) {
                //回滚事务
                Db::rollback();
                return ajax_return_adv_error('添加司机拒单明细失败');
            }
            //
            if (input('re') == 're') {
                // 查找派单
                $portionGroupInfo = Db::name('portion_traveler')->where('group_id', $group['id'])->order('id', 'desc')->find();
                if ($portionGroupInfo['isdeal']) {
                    // 已经分配旅客住宿
                    // 查找所有的住宿旅客
                    // 减少房间的消耗量
                    $data = Db::name('hotel_accommodation')->where('group_id', $group['id'])->select();
                    foreach ($data as $index => $datum) {
                        $tian = round(($datum['end_date'] - $datum['check_in_date']) / 3600 / 24);
                        // 当前的入住日期
                        $check_in_date = date('Y-m-d', $datum['check_in_date']);
                        $end_date = date('Y-m-d', $datum['end_date']);
                        // 把入住日期与退房日期的相差天数
                        $date = [$check_in_date, $end_date];
                        logs('cha', $date);
                        for ($i = 1; $i < $tian; $i++) {
                            array_push($date, date("Y-m-d", strtotime("+{$i} day", strtotime("{$check_in_date}"))));//添加的
                        }
                        // 查找旅客住宿记录
                        $room_consumption = Db::name('room_consumption')->where('date_of_stay', 'in', $date)->where('hotel_id', $datum['hotel_id'])
                            ->where('hotel_room_type_id', $datum['hotel_room_type'])->select();
                        if ($room_consumption) {
                            foreach ($room_consumption as $index2 => $item2) {
                                Db::name('room_consumption')->where('id', $item2['id'])->setDec('num');
                            }
                        }
                    }
                    // 删除派单
                    $del = Db::name('portion_traveler')->where('group_id', $group['id'])->delete();
                    $sql = Db::name('portion_traveler')->where('group_id', $group['id'])->fetchSql(true)->delete();
                    logs('sql', $sql);
                    // 删除住宿记录
                    Db::name('hotel_accommodation')->where('group_id', $group['id'])->delete();
                    logs('del', $del);
                } else {
                    $del = Db::name('portion_traveler')->where('group_id', $group['id'])->delete();
                    logs('del', $del);
                }
            }
            //司机拒单成功
//            $map['user_id'] = $editData['driver_user_id'];
//            $map['type'] = "reset_group";
//            $map['dispatch_traveler_group_id'] = $group['id'];

            $group_id = $group['id'];
            set_info($editData['driver_user_id'], '订单取消', "你的订单已被取消", 'reset_group', array('dispatch_traveler_group_id' => $group_id));
            //操作完成提交事务
            Db::commit();
            return ajax_return_adv('操作成功');

        } else {//get的请求
            $disid = input('dis_id');
            $du_id = input('du_id');
            $oid = input('oid');
            $re = input('re');
            $is_rej = input('is_rej');
            $data = DB::name('dispatch_traveler_group')
                ->where('id', $disid)
                ->field('num,dispatch_id,remark,go_date,end_date,driver_user_id,route_id,car_form,is_pickup,oid')
                ->find();
            $title = Db::name('route')->where('id', $data['route_id'])->value('title');
            $drd = DB::name('driver')
                ->where('user_id', $du_id)
                ->field('vehicle_level,driver_rank_id')
                ->find();
            $data['title'] = $title;
            $data['vehicle_level'] = $drd['vehicle_level'];
            $data['realname'] = Db::name('admin_user')->where('id', $data['driver_user_id'])->value('realname');
            $data['dr_rank_id'] = Db::name('driver_rank')->where('id', $drd['driver_rank_id'])->value('name');
            if ($data['is_pickup'] == 0) {
                $namt = Db::name('order_traveler')->where('group_id', $disid)->field('name')->select();
                foreach ($namt as $k => $v) {
                    $guest_name[] = $v['name'];
                }
                if (!empty($guest_name)) {
                    $data['guest_name'] = implode("+", $guest_name);
                } else {
                    $data['guest_name'] = null;
                }
                $data['guest_name'] = rtrim($data['guest_name'], '+');
                $data['guest_num'] = $data['num'];
            } else {
                $namt = Db::name('order_traveler')->where('oid',"in", $data['oid'])->field('name')->select();
                foreach ($namt as $k => $v) {
                    $guest_name[] = $v['name'];
                }
                if (!empty($guest_name)) {
                    $data['guest_name'] = implode("+", $guest_name);
                } else {
                    $data['guest_name'] = null;
                }
                $data['guest_name'] = rtrim($data['guest_name'], '+');
                $data['guest_num'] = $data['num'];
            }
                $list = model('DispatchTravelerGroup')->find($disid);
//                return json(['aaa' => $list ]);
//            $list = model('DispatchTravelerGroup')->find($group['id']);

//            //查询所有该分配组的信息
//            $group = Db::name('dispatch_traveler_group')
//                ->where('id',$group_id)
//                ->find();
//            if (!$group){
//                return ajax_return_adv_error('不存在该分组数据');
//            }
//            //查找分配司机的姓名
//            $driver = Db::name('admin_user')->where('id',$group['driver_user_id'])->find();
//            return view('',compact('group','driver'));
            $this->view->assign('dis_id', $disid);
            $this->view->assign('data', $data);
            $this->view->assign('du_id', $du_id);
            $this->view->assign('oid', $oid);
            $this->view->assign('list', $list);
            $this->view->assign('is_rejection', $is_rej);
            //判断是否是已接单
            if ($re == 're') {
                $this->view->assign('re', $re);
            }
            return $this->view->fetch();
        }
//        $this->view->assign("count", $list->total());
//        $this->view->assign("page", $list->render());
//        $this->view->assign('numPerPage', $list->listRows());

    }

    /**
     * 司机拒接订单
     * @params int $group_id
     * @url /admin/dispatch_traveler_group/driver_refused
     */
    public function driver_refused(Request $request)
    {
        if ($request->isPost()) {
            $editData = $request->post();
            //释放司机,同时记录司机的拒单次数
            $driverUser = Db::name('driver')->where('user_id', $editData['driver_user_id'])->find();//司机信息
            //查询该分组的数据
            $group = Db::name('dispatch_traveler_group')->where('id', $editData['id'])->find();
            $status = $group['dispatch_group_status'];
            //恢复分组的状态
            if ($group['dispatch_group_status'] != 'undistributed' || $group['dispatch_group_status'] != 'achieve' || $group['dispatch_group_status'] != 'accounts') {
                $update['dispatch_group_status'] = 'undistributed';
                $update['driver_confirm'] = false;
                $update['isreject'] = false;
                $update['dispatch_time'] = 0;
                $update['is_settlement'] = false;
                $update['settlement_time'] = 0;
                $update['settlement_time'] = 0;
                $update['driver_user_id'] = 0;
                $update['reset_time'] = NOW_TIME;
                $up = Db::name('dispatch_traveler_group')->where('id', $group['id'])->update($update);
                if (!$up) {
                    return ajax_return_adv_error('恢复分组状态失败!');
                }
            }
            if (!$driverUser) {
                return ajax_return_adv_error('不存在该司机');
            } else {
                //增加司机的拒单次数
                $up = Db::name('driver')->where('id', $driverUser['id'])->where('user_id', $editData['driver_user_id'])->setInc('number_of_refusals', 1);
                Db::name('driver')->where('id', $driverUser['id'])->where('user_id', $editData['driver_user_id'])->update(['inservice' => 0]);
                if (!$up) {
                    return ajax_return_adv_error('司机增加拒单次数失败!');
                }
            }
            //记录司机拒单的原因
            $insert = [
                'user_id' => $editData['driver_user_id'],
                'driver_id' => $driverUser['id'],
                'group_id' => $group['id'],
                'title' => $group['title'],
                'rejection_reason' => htmlspecialchars($editData['rejection_reason']),
                'create_time' => time(),
                'group_status' => $status
            ];
            //把司机拒单原因添加进表
            $insertGetId = Db::name('driver_refused')->strict(false)->insertGetId($insert);
            if (!$insertGetId) {
                return ajax_return_adv_error('添加司机拒单明细失败');
            }

            // 查找派单
            $portionGroupInfo = Db::name('portion_traveler')->where('group_id', $editData['id'])->order('id', 'desc')->find();
            if ($portionGroupInfo['isdeal']) {
                // 已经分配旅客住宿
                // 查找所有的住宿旅客
                // 减少房间的消耗量
                $data = Db::name('hotel_accommodation')->where('group_id', $editData['id'])->select();
                foreach ($data as $index => $datum) {
                    $tian = round(($datum['end_date'] - $datum['check_in_date']) / 3600 / 24);
                    // 当前的入住日期
                    $check_in_date = date('Y-m-d', $datum['check_in_date']);
                    $end_date = date('Y-m-d', $datum['end_date']);
                    // 把入住日期与退房日期的相差天数
                    $date = [$check_in_date, $end_date];
                    logs('cha', $date);
                    for ($i = 1; $i < $tian; $i++) {
                        array_push($date, date("Y-m-d", strtotime("+{$i} day", strtotime("{$check_in_date}"))));//添加的
                    }
                    // 查找旅客住宿记录
                    $room_consumption = Db::name('room_consumption')->where('date_of_stay', 'in', $date)->where('hotel_id', $datum['hotel_id'])
                        ->where('hotel_room_type_id', $datum['hotel_room_type'])->select();
                    if ($room_consumption) {
                        foreach ($room_consumption as $index2 => $item2) {
                            Db::name('room_consumption')->where('id', $item2['id'])->setDec('num');
                        }
                    }
                }
                // 删除派单
                $del = Db::name('portion_traveler')->where('group_id', $editData['id'])->delete();
                $sql = Db::name('portion_traveler')->where('group_id', $editData['id'])->fetchSql(true)->delete();
                logs('sql', $sql);
                // 删除住宿记录
                Db::name('hotel_accommodation')->where('group_id', $editData['id'])->delete();
                logs('del', $del);
            } else {
                $del = Db::name('portion_traveler')->where('group_id', $editData['id'])->delete();
                logs('del', $del);
            }

            //司机拒单成功
            $map['user_id'] = $editData['driver_user_id'];
            $map['type'] = "reset_group";
            $map['dispatch_traveler_group_id'] = $group['id'];
            $group_id = $group['id'];
            set_info($editData['driver_user_id'], '订单取消', "你的订单已被取消，订单编号{$group_id}", 'reset_group', array('dispatch_traveler_group_id' => $group_id));

            return ajax_return_adv('操作成功');

        } else {//get的请求
            $group_id = input('group_id');
            //查询所有该分配组的信息
            $group = Db::name('dispatch_traveler_group')
                ->where('id', $group_id)
                ->find();
            if (!$group) {
                return ajax_return_adv_error('不存在该分组数据');
            }
            //查找分配司机的姓名
            $driver = Db::name('admin_user')->where('id', $group['driver_user_id'])->find();
            return view('', compact('group', 'driver'));
        }
    }

    /**
     * 重新分配
     * @return mixed
     */
    public function in_again()
    {

        $data = input();

        $map['dtg.dispatch_group_status'] = 'undistributed';
        //派车单号
        if ($data['id']) {
            $map['dtg.id'] = array('like', "%{$data['id']}%");
        }
        //客人
        if ($data['grname']) {
            $mapu['name'] = array('like', "%{$data['grname']}%");
            $group_id = Db::name('order_traveler')->where($mapu)->field('group_id')->select();
            if ($group_id) {
                foreach ($group_id as $k => $v) {
                    $dis_id[] = $v['group_id'];
                }
                $map['dtg.id'] = array('in', $dis_id);
            }
        }
        //司机
        if ($data['realname']) {
            $mapa['realname'] = array('like', "%{$data['realname']}%");
            $au = Db::name('admin_user')->where($mapa)->field('id')->select();
            if ($au) {
                foreach ($au as $k => $v) {
                    $au_id[] = $v['id'];
                }
                $map['dtg.driver_user_id'] = array('in', $au_id);
            }
        }
//        return json(['aa' => $data]);
        //出行日期
        if ($data['start_time'] && $data['end_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        } elseif ($data['start_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['start_time'] . " 23:59:59")]);
        } elseif ($data['end_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['end_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        }
        //用车形式
        if ($data['car_form']) {
            $map['or.car_form'] = array('=', $data['car_form']);
        }

        $map['isreject'] = false;
        $listRows = $this->request->param('numPerPage') ? 20 : Config::get("paginate.list_rows");
        $list = DB('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_dispatch_order dor', 'dor.dispatch_id=dtg.dispatch_id', 'left')
            ->join('tp_order or', 'or.id=dor.oid', 'left')
            ->join('tp_driver dr', 'dr.user_id=dtg.driver_user_id', 'left')
            ->field('dtg.num,dtg.is_pickup,dtg.oid as dtg_oid,dtg.route_id,dtg.comment_praise,dtg.comment_negative,dtg.id,dtg.car_confirm,dtg.remark,dtg.dispatch_id,dtg.driver_user_id,dor.oid,dtg.go_date as start_time,dtg.end_date as end_time,dtg.car_form,dr.vehicle_level,dr.driver_rank_id')
            ->where($map)
            ->order("dtg.id desc")
            ->group("dor.dispatch_id")
            ->paginate($listRows, false, ['query' => $this->request->get()]);
//        $list_data = $list->toArray();
//        if ($list_data['data']){
//            foreach ($list_data['data'] as $ldk=>$ldv){
//                //查找客人姓名
//                $travelers=Db::name("dispatch_traveler")->alias('dt')
//                    ->join("tp_order_traveler ot","ot.id=dt.traveler_id","left")
//                    ->where('dt.group_id',$ldv['id'])
//                    ->field('ot.*')
//                    ->select();
//                $booking_people_name = '';
//                foreach ($travelers as $tk=>$tv){
//                    $booking_people_name .= $tv['name'].'+';
//                }
//                $booking_people_name = rtrim($booking_people_name,'+');
//                $list_data['data'][$ldk]['booking_people_name'] = $booking_people_name;
//            }
//        }
        $show = 1;
        $this->view->assign('list', $list);
//        $this->view->assign('list_data',$list_data['data']);
        $this->view->assign('show', $show);
//        $this->view->assign('searchCondition',$searchData);//搜索条件
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 导出数据到excel
     */
//    public function export_to_excel(Request $request)
//    {
//        $data = input();
//
//        Vendor('PHPExcel.PHPExcel');
//        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
//        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
//        //实例化
//        $export_excel = new \PHPExcel();
//        //设置文档属性
//        $writer = \PHPExcel_IOFactory::createWriter($export_excel,'Excel2007');
//        //设置内容
//        $export_sheet = $export_excel->getActiveSheet();
//        for ($l = 0; $l < 26; $l++) {
//            $letter[] = chr($l+65);
//        }
//        $countChr = count($letter);
//        for ($j = 0; $j < $countChr; $j++) {
//            for ($k = 0; $k < $countChr; $k++) {
//                $letter[] = $letter[$j].$letter[$k];
//            }
//        }
//        $tableHeader = ['ID','分配ID','数量','司机','是否确认','出发日期','结束日期','状态','是否结算','结算方式',
//            '结算佣金','结算时间','用车形式','标题','重置时间','申请结算时间','完成时间','拒接时间','是否拒接结算'
//        ,'拒接结算时间','拒接结算原因','status','是否删除','创建时间','是否拒接','拒接原因','车型','产品_id','备注'
//        ,'旧的司机用户ID','旧的司机用户名','申请中止的原因','是否申请中止','申请中止时间','好评数','差评数','车调确认','乘客'];
//        $li_length = count($letter);//设置单元格的宽度
//        for ($li=0;$li<$li_length;$li++){
//            switch ($letter[$li]){
//                case 'A':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
//                case 'B':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
//                case 'C':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);break;
//                case 'D':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
//                case 'E':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
//                case 'G':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
//                case 'H':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
//                case 'I':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
//                case 'J':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
//                case 'K':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
//                case 'AK':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
//                default:
//                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);
//            }
//        }
//        $tableLength = count($tableHeader);
//        for ($i = 0; $i < $tableLength; $i++){
//            $export_sheet->setCellValue("$letter[$i]1","$tableHeader[$i]");
//        }
//        if($this::$isdelete){
//            $map['dtg.isdelete']=1;
//        }else{
//            $map['dtg.isdelete']=0;
//        }
//        if ($data['go_date']){
//            $map['dtg.go_date'] =['eq',$data['go_date']];//等于
//        }
//        if ($data['sales_id']){
//            $map['dtg.sales_id'] =['eq',$data['sales_id']];//等于
//        }
//        if ($data['driver_user']){
//            $driverUserInfos = Db::name('admin_user')->where('realname','like','%'.$data['driver_user'].'%')
//                                        ->field('id,realname')->select();
//            $driverIds = '';
//            foreach ($driverUserInfos as $dk=>$dv){
//                $driverIds .= $dv['id'].',';
//            }
//            $driverIds = rtrim($driverIds,',');
//            $map['dtg.driver_user_id'] =['in',$driverIds];
//        }
//        if($data['is_settlement']==1){
//            $map['dtg.is_settlement']=1;
//        }elseif ($data['is_settlement']==2){
//            $map['dtg.is_settlement']=0;
//        }
//        if ($data['dispatch_group_status']){
//            $map['dtg.dispatch_group_status']=$data['dispatch_group_status'];//进行中
//            $dispatch_group_status = $data['dispatch_group_status'];
//            switch ($dispatch_group_status){
//                case 'proceed': $tableName = '进行中'; break;
//                case 'achieve': $tableName = '已完成'; break;
//                case 'accounts': $tableName = '已结算'; break;
//                case 'all': $tableName = '全部'; break;
//                default: $tableName = '测试导出数据';
//            }
//        }
//        if ($data['search']){
//            switch ($data['search']){
//                case 'proceed': $tableName = '进行中'; break;
//                case 'achieve': $tableName = '已完成'; break;
//                case 'accounts': $tableName = '已结算'; break;
//                case 'all': $tableName = '全部'; break;
//                default: $tableName = '测试导出数据';
//            }
//        }
//        if ($data['comment_status'] == 1){
//            $map['dtg.comment_status'] = 1;
//        }elseif ($data['comment_status'] == 2){
//            $map['dtg.comment_status'] = 0;
//        }
//
//        //选择导出数据
//        if ($data['id']){
//            $id = implode($data['id'],',');
//            $map['dtg.id'] = ['in',$id];
//        }
//
//        //下单人
//        if ($data['booking_people_name']){
//            $name['name'] = ['like','%'.$data['booking_people_name'].'%'];
//            $travelPeople = Db::name('order_traveler')->where($name)->field('id,name,oid,group_id')->select();
//            $travelPeopleIds = '';
//            foreach ($travelPeople as $tpk=>$tpv){
//                if (!empty($tpv['group_id'])){
//                    $travelPeopleIds .= $tpv['group_id'].',';
//                }
//            }
//            $travelPeopleIds = rtrim($travelPeopleIds,',');
//            $map['dtg.id'] = ['in',$travelPeopleIds];
//        }
//        if ($data['car_form']){
//            $map['dtg.car_form'] = ['like','%'.$data['car_form'].'%'];
//        }
//        if ($data['remark']){
//            $map['dtg.remark'] = ['like','%'.$data['remark'].'%'];
//        }
//        //查询要填充表格数据
//        $list = Db::name('dispatch_traveler_group')
//            ->alias('dtg')
//            ->join('tp_admin_user u','u.id=dtg.driver_user_id','left')
//            ->field('dtg.*,u.realname as driver_user_id')
//            ->where($map)
//            ->order("dtg.id desc")
//            ->select();
//        foreach ($list as $lk=>$lv){
//            $travelers=Db::name("dispatch_traveler")->alias('dt')
//                ->join("tp_order_traveler ot","ot.id=dt.traveler_id","left")
//                ->where('dt.group_id',$lv['id'])
//                ->field('ot.*')
//                ->select();
//            $oid = '';
//            $booking_people_name = '';
//            foreach ($travelers as $tlk=>$tlv){
//                $booking_people_name .= $tlv['name'].'+';
//                $oid .= $tlv['oid'].',';
//            }
//            $list[$lk]['booking_people_name'] = rtrim($booking_people_name,'+');
//            if ($lv['driver_confirm'] == 1){
//                $list[$lk]['driver_confirm'] = '是确认';
//            }else{
//                $list[$lk]['driver_confirm'] = '不确认';
//            }
//            $list[$lk]['go_date'] = empty($lv['go_date']) ? '':date('Y-m-d H:i:s',$lv['go_date']);
//            $list[$lk]['end_date'] = empty($lv['end_date']) ? '':date('Y-m-d H:i:s',$lv['end_date']);
//            $list[$lk]['reset_time'] = empty($lv['reset_time']) ? '':date('Y-m-d H:i:s',$lv['reset_time']);
//            $list[$lk]['settlement_apply_time'] = empty($lv['settlement_apply_time']) ? '':date('Y-m-d H:i:s',$lv['settlement_apply_time']);
//            $list[$lk]['settlement_time'] = empty($lv['settlement_time']) ? '':date('Y-m-d H:i:s',$lv['settlement_time']);//结算时间
//            $list[$lk]['achieve_time'] = empty($lv['achieve_time']) ? '':date('Y-m-d H:i:s',$lv['achieve_time']);
//            $list[$lk]['reject_time'] = empty($lv['reject_time']) ? '':date('Y-m-d H:i:s',$lv['reject_time']);
//            $list[$lk]['reject_settlement_time'] = empty($lv['reject_settlement_time']) ? '':date('Y-m-d H:i:s',$lv['reject_settlement_time']);
//            $list[$lk]['create_time'] = empty($lv['create_time']) ? '':date('Y-m-d H:i:s',$lv['create_time']);
//            $list[$lk]['suspension_time'] = empty($lv['suspension_time']) ? '':date('Y-m-d H:i:s',$lv['suspension_time']);
//            $list[$lk]['isdelete'] = empty($lv['isdelete']) ?  '未删除' : '已删除';
//            $list[$lk]['isreject'] = empty($lv['isreject']) ?  '未拒绝' : '是拒绝';
//            $list[$lk]['car_type_id'] = empty($lv['car_type_id']) ?  '' : Db::name('car_type')->where('id',$lv['car_type_id'])->value('car_type');
//            unset($list[$lk]['reverse_id']);
//            if ($lv['dispatch_group_status'] == 'proceed'){
//                $list[$lk]['dispatch_group_status'] = '进行中';
//            }elseif ($lv['dispatch_group_status'] == 'achieve'){
//                $list[$lk]['dispatch_group_status'] = '已完成';
//            }elseif ($lv['dispatch_group_status'] == 'sendorders'){
//                $list[$lk]['dispatch_group_status'] = '已派单';
//            }elseif ($lv['dispatch_group_status'] == 'undistributed'){
//                $list[$lk]['dispatch_group_status'] = '未分配';
//            }elseif ($lv['dispatch_group_status'] == 'accounts'){
//                $list[$lk]['dispatch_group_status'] = '已结算';
//            }
//            switch ($lv['is_settlement']){
//                case 0:  $list[$lk]['is_settlement'] = '未结算'; break;
//                case 1:  $list[$lk]['is_settlement'] = '已结算'; break;
//            }
//            switch ($lv['is_reject_settlement']){
//                case 0:  $list[$lk]['is_reject_settlement'] = '不拒接结算'; break;
//                case 1:  $list[$lk]['is_reject_settlement'] = '是拒接结算'; break;
//            }
//            switch ($lv['is_suspend']){
//                case 1: $list[$lk]['is_suspend'] = '不是申请中止'; break;
//                case 2: $list[$lk]['is_suspend'] = '是申请中止'; break;
//            }
//            switch ($lv['car_confirm']){
//                case null: $list[$lk]['car_confirm'] = '未确认'; break;
//                case 1: $list[$lk]['car_confirm'] = '已确认'; break;
//            }
//         }
//        //定义table键
//        if (!empty($list)){
//            $tableKey = array_keys($list[0]);
//            //填充表格信息
//            $tableKeyLength = count($tableKey);
//            foreach ($list as $tk=>$tv){
//                $tk += 2;
//                for ($i = 0; $i < $tableKeyLength; $i++){
//                    $export_sheet->setCellValue("$letter[$i]".$tk,$tv[$tableKey[$i]]);
//                }
//            }
//        }
//        $fileName = date('YmdHis',time())."车配匹配管理-{$tableName}数据.xls";
//        $fileName = iconv('utf-8','gb2312',$fileName);
//        ob_end_clean();
//        if ($request->isGet()){
//            header('Content-Type:application/force-download');
//            header('Content-Type:application/octet-stream');
//            header('Content-Type:application/download');
//            header('Content-Disposition:inline;filename='.$fileName);
//            header('Content-Transfer-Encoding:binary');
//            header('Cache-Control:must-revalidate,post-check=0');
//            header('Pragma:no-cache');
//            $writer->save('php://output');
//            exit();
//        }else{
//            // 保存文件到服务器上
//            $path = ROOT_PATH."public/excel";
//            // 判断文件是否存在
//            if (!file_exists($path)){
//                mkdir($path,0777,true);
//            }
//            $fileName = iconv('gb2312','utf-8',$fileName);
//            $file = $path."/{$fileName}";
//            $writer->save($file);
//            $url =$request->domain()."/excel/{$fileName}";
//            return ajax_return_adv($url,'','','','','',5);
//        }
//    }
    public function export_to_excel(Request $request)
    {
        $data = input();
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel, 'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l + 65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j] . $letter[$k];
            }
        }
        $dis_stat = input('dis_status');
        $is_re = input('is_re');
        $account = input('account');
        if ($dis_stat == 'achieve') {
            $tableHeader = ['派车单号', '线路名称', '司机', '司机等级', '车辆等级', '用车形式', '客人姓名', '客人数量', '好评数', '差评数', '出发日期', '结束日期', '备注'];
            $tablename = '已完成';

        } elseif ($dis_stat == 'sendorders') {
            $tableHeader = ['派车单号', '线路名称', '司机', '司机等级', '车辆等级', '用车形式', '客人姓名', '客人数量', '出发日期', '结束日期', '备注'];
            $tablename = '派单中';

        } elseif ($dis_stat == 'proceed') {

            $tableHeader = ['派车单号', '线路名称', '司机', '司机等级', '车辆等级', '用车形式', '客人姓名', '客人数量', '出发日期', '结束日期', '备注'];
            $tablename = '进行中';
        } elseif ($dis_stat == 'receiving') {

            $tableHeader = ['派车单号', '线路名称', '司机', '司机等级', '车辆等级', '用车形式', '客人姓名', '客人数量', '出发日期', '结束日期', '备注'];
            $tablename = '已接单';
            $map['dtg.driver_confirm'] = '1';
        } elseif ($is_re == 1) {
            $tableHeader = ['派车单号', '线路名称', '司机', '司机等级', '车辆等级', '用车形式', '客人姓名', '客人数量', '出发日期', '结束日期', '备注', '更换原因', '司机金额', '记录时间'];
            $tablename = '更换司机记录';
            $map['is_rejection'] = array('=', 1);
        } elseif ($is_re == 2) {
            $tableHeader = ['派车单号', '线路名称', '司机', '司机等级', '车辆等级', '用车形式', '客人姓名', '客人数量', '出发日期', '结束日期', '备注', '中止原因', '司机金额', '记录时间'];
            $tablename = '中止司机记录';
            $map['is_rejection'] = array('=', 2);
        } elseif ($account == 1) {
            $tableHeader = ['派车单信息', '司机信息', '客人信息', '评价信息', '时间', '结算信息', '备注'];
            $tablename = '申请结算中';
            $map['dtg.is_apply_settlement'] = '1';
            $map['dtg.dispatch_group_status'] = 'accounts';
        } elseif ($account == 2) {
            $tableHeader = ['派车单信息', '司机信息', '客人信息', '评价信息', '时间', '结算信息', '拒绝原因', '备注'];
            $tablename = '结算驳回';
            $map['dtg.dispatch_group_status'] = 'accounts';
            $map['dtg.is_reject_settlement'] = '1';
        } elseif ($account == 3) {
            $tableHeader = ['派车单信息', '司机信息', '客人信息', '评价信息', '时间', '结算信息', '备注'];
            $tablename = '已结算';
            $map['dtg.dispatch_group_status'] = 'accounts';
            $map['dtg.is_settlement'] = '1';
            $map['dtg.isdelete'] = '0';
        }
        $li_length = count($letter);//设置单元格的宽度
        for ($li = 0; $li < $li_length; $li++) {
            switch ($letter[$li]) {
                case 'A':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'B':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'C':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'D':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'E':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'G':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'H':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'I':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'J':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'K':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'AK':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                default:
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);
            }
        }
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++) {
            $export_sheet->setCellValue("$letter[$i]1", "$tableHeader[$i]");
        }
        if (empty($account)) {
            if (empty($is_re)) {
                $map['dtg.dispatch_group_status'] = $dis_stat;
                $map['isreject'] = false;
                $list = DB('dispatch_traveler_group')
                    ->alias('dtg')
                    ->join('tp_dispatch_order dor', 'dor.dispatch_id=dtg.dispatch_id', 'left')
                    ->join('tp_order or', 'or.id=dor.oid', 'left')
                    ->join('tp_driver dr', 'dr.user_id=dtg.driver_user_id', 'left')
                    ->field('dtg.num,dtg.is_pickup,dtg.oid as dtg_oid,dtg.route_id,dtg.comment_praise,dtg.comment_negative,dtg.id,dtg.remark,dtg.dispatch_id,dtg.driver_user_id,dor.oid,dtg.go_date as start_time,dtg.end_date as end_time,dtg.car_form,dr.vehicle_level,dr.driver_rank_id')
                    ->where($map)
                    ->order("dtg.id desc")
                    ->group("dor.dispatch_id")
                    ->select();
            } else { //获取记录的数据
                $list = DB('driver_rejection_write')
                    ->where($map)->select();
            }

            foreach ($list as $k => $v) {
                if (empty($is_re)) {
                    $realname = Db::name('admin_user')->where('id', $v['driver_user_id'])->value('realname'); //司机
                    $dr_rank_name = Db::name('driver_rank')->where('id', $v['driver_rank_id'])->value('name'); //司机等级
                    if ($v['is_pickup'] == 0) {
                        $namt = null;
                        $u_num = null;
                        $user_name = null;
                        $namt = Db::name('order_traveler')->where('group_id', $v['id'])->field('name')->select(); //客人名称
                        $u_num = $v['num'];
                        $uname = [];
                        foreach ($namt as $kk => $vv) {
                            $uname[] = $vv['name'];
                        }
                        $user_name = implode("+", $uname);
                        $user_name = rtrim($user_name, '+');
                    } else {
                        $namt = null;
                        $u_num = null;
                        $user_name = null;
                        $user_name = $v['guest_name'];
                        $u_num = $v['guest_num'];
                    }
                } else { //记录的数据
                    $realname = $v['realname'];
                    $dr_rank_name = $v['dr_rank_name'];
                    $user_name = $v['guest_name'];
                    $u_num = $v['guest_num'];
                }

                $lists[$k]['id'] = empty($v['id']) ? '' : $v['id'];
                if (isset($v['is_pickup'])) {
                    $title = Db::name('route')->where('id', $v['route_id'])->value('title');
                    $lists[$k]['title'] = empty($title) ? '' : $title;
                } else {
                    $lists[$k]['title'] = empty($v['title']) ? '' : $v['title'];
                }
                $lists[$k]['realname'] = empty($realname) ? '' : $realname;
                $lists[$k]['dr_rank_name'] = empty($dr_rank_name) ? '' : $dr_rank_name;
                $lists[$k]['vehicle_level'] = empty($v['vehicle_level']) ? '' : $v['vehicle_level'];
                $lists[$k]['car_form'] = empty($v['car_form']) ? '' : $v['car_form'];
                $lists[$k]['user_name'] = empty($user_name) ? '' : $user_name;
                $lists[$k]['user_num'] = empty($u_num) ? 0 : $u_num;
                //判断是否是已完成 加入评论数据
                if ($dis_stat == 'achieve') {
                    $lists[$k]['comment_praise'] = empty($v['comment_praise']) ? 0 : $v['comment_praise'];
                    $lists[$k]['comment_negative'] = empty($v['comment_negative']) ? 0 : $v['comment_negative'];
                }
                $lists[$k]['start_time'] = empty($v['start_time']) ? '' : date('Y-m-d H:i:s', $v['start_time']);
                $lists[$k]['end_time'] = empty($v['end_time']) ? '' : date('Y-m-d H:i:s', $v['end_time']);
                $lists[$k]['remark'] = empty($v['remark']) ? '' : $v['remark'];
                if (!empty($is_re)) {
                    $lists[$k]['rejection_reason'] = empty($v['rejection_reason']) ? '' : $v['rejection_reason'];
                    $lists[$k]['dir_price'] = empty($v['dir_price']) ? 0 : $v['dir_price'];
                    $lists[$k]['create_time'] = empty($v['create_time']) ? '' : date('Y-m-d H:i:s', $v['create_time']);
                }

            }
        } else {
            $map['isreject'] = false;
            $list = Db::name('dispatch_traveler_group')
                ->alias('dtg')
                ->join('tp_admin_user u', 'u.id=dtg.driver_user_id', 'left')
                ->field('dtg.*,u.realname')
                ->where($map)
                ->order("dtg.id desc")
                ->select();

            foreach ($list as $k => $v) {
                if ($v['is_pickup'] == '1') { //接机单
                    //查找客人姓名
                    $travelers = Db::name("order_traveler")
                        ->where('oid', $v['oid'])
                        ->select();
                } else {
                    //查找客人姓名
                    $travelers = Db::name("dispatch_traveler")->alias('dt')
                        ->join("tp_order_traveler ot", "ot.id=dt.traveler_id", "left")
                        ->where('dt.group_id', $v['id'])
                        ->field('ot.*')
                        ->select();
                }
                $booking_people_name = '';
                foreach ($travelers as $tk => $tv) {
                    $booking_people_name .= $tv['name'] . '+';
                }
                $booking_people_name = rtrim($booking_people_name, '+');
                $booking_people_num = count($travelers);
                if ($v['is_reach_standard'] == '0') {
                    $is_reach_standard = '否';
                } else {
                    $is_reach_standard = '是';
                }
                $route_title = Db::name('route')->where('id', $v['route_id'])->value('title');
                $driver = Db::name('driver')->where('id', $v['driver_user_id'])->field('driver_rank_id,vehicle_level')->find();
                $dis_id = empty($v['id']) ? '' : $v['id'];
                $dis_title = empty($v['title']) ? '' : $v['title'];
                $dis_route_title = empty($route_title) ? '' : $route_title;
                $realname = empty($v['realname']) ? '' : $v['realname'];
                $driver_rank_id = empty($driver['driver_rank_id']) ? '' : $driver['driver_rank_id'];
                $vehicle_level = empty($driver['vehicle_level']) ? '' : $driver['vehicle_level'];
                $booking_people_name = empty($booking_people_name) ? '' : $booking_people_name;
                $booking_people_num = empty($booking_people_num) ? 0 : $booking_people_num;
                $car_form = empty($v['car_form']) ? '' : $v['car_form'];
                $comment_praise = empty($v['comment_praise']) ? '' : $v['comment_praise'];
                $comment_negative = empty($v['comment_negative']) ? '' : $v['comment_negative'];
                $go_date = empty($v['go_date']) ? '' : date('Y-m-d H:i', $v['go_date']);
                $end_date = empty($v['end_date']) ? '' : date('Y-m-d H:i', $v['end_date']);
                $apply_settlement_time = empty($v['apply_settlement_time']) ? '' : date('Y-m-d H:i', $v['apply_settlement_time']);
                $reject_settlement_time = empty($v['reject_settlement_time']) ? '' : date('Y-m-d H:i', $v['reject_settlement_time']);
                $settlement_time = empty($v['settlement_time']) ? '' : date('Y-m-d H:i', $v['settlement_time']);
                $feedback = empty($v['feedback']) ? '' : $v['feedback'];
                $driver_fee = empty($v['driver_fee']) ? '' : $v['driver_fee'];
                $driver_compensation = empty($v['driver_compensation']) ? '' : $v['driver_compensation'];
                $company_compensation = empty($v['company_compensation']) ? '' : $v['company_compensation'];
                $reject_settlement_reason = empty($v['reject_settlement_reason']) ? '' : $v['reject_settlement_reason'];
                $remark = empty($v['remark']) ? '' : $v['remark'];
                $settlement_mode = empty($v['settlement_mode']) ? '' : $v['settlement_mode'];
                $settlement_money = empty($v['settlement_money']) ? '' : $v['settlement_money'];
                $lists[$k]['dis_data'] = '派车单号:' . $dis_id . '、标题:' . $dis_title . '、路线名称:' . $dis_route_title;
                $lists[$k]['dr_data'] = '司机姓名:' . $realname . '、司机等级:' . $driver_rank_id . '、车辆等级:' . $vehicle_level . '、用车形式:' . $car_form;
                $lists[$k]['user_data'] = '客人姓名:' . $booking_people_name . '、客人数量:' . $booking_people_num;
                $lists[$k]['pl_data'] = '好评数:' . $comment_praise . '、差评数:' . $comment_negative . '、好评比率:' . $feedback . '%、是否达标:' . $is_reach_standard;
                if ($account == 1) {
                    $lists[$k]['tiem_data'] = '出发时间:' . $go_date . '、结束时间:' . $end_date . '申请结算时间:' . $apply_settlement_time;
                } elseif ($account == 2) {
                    $lists[$k]['tiem_data'] = '出发时间:' . $go_date . '、结束时间:' . $end_date . '、申请结算时间:' . $apply_settlement_time . '、拒绝结算时间:' . $reject_settlement_time;
                } elseif ($account == 3) {
                    $lists[$k]['tiem_data'] = '出发时间:' . $go_date . '、结束时间:' . $end_date . '、申请结算时间:' . $apply_settlement_time . '、结算时间:' . $settlement_time;
                }
                if ($account == 3) {
                    $lists[$k]['dr_pr'] = '司机费用:' . $driver_fee . '、司机补偿金:' . $driver_compensation . '、公司补偿金:' . $company_compensation . '、结算方式:' . $settlement_mode . '、结算佣金:' . $settlement_money;
                } else {
                    $lists[$k]['dr_pr'] = '司机费用:' . $driver_fee . '、司机补偿金:' . $driver_compensation . '、公司补偿金:' . $company_compensation;
                }
                if ($account == 2) {
                    $lists[$k]['$reject_settlement_reason'] = $reject_settlement_reason;
                }
                $lists[$k]['remark'] = $remark;
            }

        }
        //定义table键
        if (!empty($lists)) {
            $tableKey = array_keys($lists[0]);

            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($lists as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);

                }
            }
        }

        $fileName = date('YmdHis', time()) . "车配匹配管理-{$tablename}数据.xls";
        $fileName = iconv('utf-8', 'gb2312', $fileName);
        ob_end_clean();
        if ($request->isGet()) {
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename=' . $fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        } else {
            // 保存文件到服务器上
            $path = ROOT_PATH . "public/excel";
            // 判断文件是否存在
            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            $fileName = iconv('gb2312', 'utf-8', $fileName);
            $file = $path . "/{$fileName}";
            $writer->save($file);
            $url = $request->domain() . "/excel/{$fileName}";
            return ajax_return_adv($url, '', '', '', '', '', 5);
        }
    }

    /**
     * 未分配
     * @return mixed
     */
    public function in_undistributed()
    {

        $map['dtg.dispatch_group_status'] = 'undistributed';
        $data = input();
        if ($data['go_date']) {
            $map['dtg.go_date'] = array("between", [strtotime($data['go_date'] . " 00:00:00"), strtotime($data['go_date'] . " 23:59:59")]);

        }

        if ($data['sales_id']) {
            $map['dtg.sales_id'] = array('in', $data['sales_id']);
        }

        if ($data['dispatch_group_status']) {
            $map['dtg.dispatch_group_status'] = $data['dispatch_group_status'];
        }
        if ($data['car_form']) {
            $map['dtg.car_form'] = array('like', "%{$data['car_form']}%");
        }
        if ($data['remark']) {
            $map['dtg.remark'] = array('like', "%{$data['remark']}%");
        }
        if ($data['is_settlement'] || $data['is_settlement'] === "0") {
            $map['dtg.is_settlement'] = $data['is_settlement'];
        }
        if ($data['driver_user']) {
            $map['u.realname'] = array('like', "%{$data['driver_user']}%");
        }
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
        $list = DB('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_admin_user u', 'u.id=dtg.driver_user_id', 'left')
            ->field('dtg.*,u.realname')
            ->where($map)
            ->order("dtg.id desc")
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $this->view->assign('list', $list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 已完成
     * @return mixed
     */
    public function in_achieve()
    {

        $map['dtg.dispatch_group_status'] = 'achieve';

        $data = input();
        //派车单号
        if ($data['id']) {
            $map['dtg.id'] = array('like', "%{$data['id']}%");
        }
        //客人
        if ($data['grname']) {
            $mapu['name'] = array('like', "%{$data['grname']}%");
            $group_id = Db::name('order_traveler')->where($mapu)->field('group_id')->select();
            if ($group_id) {
                foreach ($group_id as $k => $v) {
                    $dis_id[] = $v['group_id'];
                }
                $map['dtg.id'] = array('in', $dis_id);
            }
        }
        //司机
        if ($data['realname']) {
            $mapa['realname'] = array('like', "%{$data['realname']}%");
            $au = Db::name('admin_user')->where($mapa)->field('id')->select();
            if ($au) {
                foreach ($au as $k => $v) {
                    $au_id[] = $v['id'];
                }
                $map['dtg.driver_user_id'] = array('in', $au_id);
            }
        }
        //出行日期
        if ($data['start_time'] && $data['end_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        } elseif ($data['start_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['start_time'] . " 23:59:59")]);
        } elseif ($data['end_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['end_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        }
        //用车形式
        if ($data['car_form']) {
            $map['dtg.car_form'] = array('=', $data['car_form']);
        }
        $map['isreject'] = false;
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
//        $list = DB('dispatch_traveler_group')
//            ->alias('dtg')
//            ->join('tp_dispatch_order dor','dor.dispatch_id=dtg.dispatch_id','left')
//            ->join('tp_order or','or.id=dor.oid','left')
//            ->join('tp_driver dr','dr.user_id=dtg.driver_user_id','left')
//            ->field('dtg.num,dtg.is_pickup,dtg.oid as dtg_oid,dtg.route_id,dtg.comment_praise,dtg.comment_negative,dtg.id,dtg.car_confirm,dtg.remark,dtg.dispatch_id,dtg.driver_user_id,dor.oid,dtg.go_date as start_time,dtg.end_date as end_time,dtg.car_form,dr.vehicle_level,dr.driver_rank_id')
//            ->where($map)
//            ->order("dtg.id desc")
//            ->group("dor.dispatch_id")
//            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $list = DB('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_dispatch d', 'd.id=dtg.dispatch_id', 'left')
            ->join('tp_driver dr', 'dr.user_id=dtg.driver_user_id', 'left')
            ->field('dtg.num,dtg.is_pickup,dtg.oid as dtg_oid,dtg.car_confirm,dtg.route_id,dtg.id,dtg.remark,dtg.dispatch_id,dtg.driver_user_id,dtg.go_date as start_time,dtg.end_date as end_time,dtg.car_form,dr.vehicle_level,dr.driver_rank_id')
            ->where($map)
            ->order("dtg.id desc")
            ->group("d.id")
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $show = 4;
        $this->view->assign('list', $list);
        $this->view->assign('show', $show);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

//    /**
//     * 已结算
//     * @return mixed
//     */
//    public function in_accounts(){
//
//        $map['dtg.dispatch_group_status']='accounts';
//
//        $data=input();
//        if($data['go_date']){
//            $map['dtg.go_date'] = array("between",[strtotime($data['go_date']." 00:00:00"),strtotime($data['go_date']." 23:59:59")]);
//
//        }
//        $url = '/admin/dispatch_traveler_group/in_proceed_html';
//        if ($data){
//            foreach ($data as $dk=>$dv){
//                if ($dk == $url){
//                    unset($data[$dk]);
//                }
//                if (!empty($dv)){
//                    $searchData[$dk] = $dv;
//                }
//            }
//            $searchData['dispatch_group_status'] = 'accounts';
//        }else{
//            $searchData['dispatch_group_status'] = 'accounts';
//        }
//        if($data['sales_id']){
//            $map['dtg.sales_id']=array('in',$data['sales_id']);
//        }
//        //下单人
//        if ($data['booking_people_name']){
//            $name['name'] = ['like','%'.$data['booking_people_name'].'%'];
//            $travelPeople = Db::name('order_traveler')->where($name)->field('id,name,oid,group_id')->select();
//            $travelPeopleIds = '';
//            foreach ($travelPeople as $tpk=>$tpv){
//                if (!empty($tpv['group_id'])){
//                    $travelPeopleIds .= $tpv['group_id'].',';
//                }
//            }
//            $travelPeopleIds = rtrim($travelPeopleIds,',');
//            $map['dtg.id'] = ['in',$travelPeopleIds];
//        }
//        if($data['dispatch_group_status']){
//            $map['dtg.dispatch_group_status']=$data['dispatch_group_status'];
//        }
//        if($data['car_form']){
//            $map['dtg.car_form']=array('like',"%{$data['car_form']}%");
//        }
//        if($data['remark']){
//            $map['dtg.remark']=array('like',"%{$data['remark']}%");
//        }
//        if($this::$isdelete){
//            $map['dtg.isdelete']=1;
//        }else{
//            $map['dtg.isdelete']=0;
//        }
//        if($data['is_settlement']||$data['is_settlement']==="0"){
//            $map['dtg.is_settlement']=$data['is_settlement'];
//        }
//        if($data['driver_user']){
//            $map['u.realname']=array('like',"%{$data['driver_user']}%");
//        }
//        $listRows = $this->request->param('numPerPage') ? : Config::get("paginate.list_rows");
//        $list = Db::name('dispatch_traveler_group')
//            ->alias('dtg')
//            ->join('tp_admin_user u','u.id=dtg.driver_user_id','left')
//            ->field('dtg.*,u.realname')
//            ->where($map)
//            ->order("dtg.id desc")
//            ->paginate($listRows, false, ['query' => $this->request->get()]);
//        $list_data = $list->toArray();
//        if ($list_data['data']){
//            foreach ($list_data['data'] as $ldk=>$ldv){
//                //查找客人姓名
//                $travelers=Db::name("dispatch_traveler")->alias('dt')
//                    ->join("tp_order_traveler ot","ot.id=dt.traveler_id","left")
//                    ->where('dt.group_id',$ldv['id'])
//                    ->field('ot.*')
//                    ->select();
//                $booking_people_name = '';
//                foreach ($travelers as $tk=>$tv){
//                    $booking_people_name .= $tv['name'].'+';
//                }
//                $booking_people_name = rtrim($booking_people_name,'+');
//                $list_data['data'][$ldk]['booking_people_name'] = $booking_people_name;
//            }
//        }
//        $show = 1;
//        $this->view->assign('list',$list);
//        $this->view->assign('list_data',$list_data['data']);
//        $this->view->assign('show',$show);
//        $this->view->assign('searchCondition',$searchData);//搜索条件
//        $this->view->assign("count", $list->total());
//        $this->view->assign("page", $list->render());
//        $this->view->assign('numPerPage', $list->listRows());
//        return $this->view->fetch();
//    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        if (!$this->request->isAjax()) {

            $car_types = Db::name('car_type')->select();
            $this->view->assign("car_types", $car_types);
            $driver_users = Db::name('driver')->alias('d')
                ->join('tp_admin_user u', 'u.id=d.user_id', 'left')
                ->field("u.*")
                ->select();
            $this->view->assign("driver_users", $driver_users);
            return $this->view->fetch('edit');
        }
        // 启动事务
        Db::startTrans();
        try {
            $input = input();

            $input['go_date'] = strtotime($input['go_date']);
            $input['end_date'] = strtotime($input['end_date']);
            $group = $input;
            if (!empty($group['go_date']) && !empty($group['end_date']) && ($group['go_date'] > $group['end_date'])) {
                return ajax_return_adv_error('订单的开始日期不能大于结束日期');
            }
            $group["traveler_ids"] = $input['traveler']['id'];

            //分组

            $model_group = new \app\common\model\DispatchTravelerGroup();
            $group_id = $model_group->insert_group($group);
            // 提交事务
            Db::commit();
            return ajax_return_adv();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ajax_return_error();
        }

    }

    /**
     * 完成订单(确认完成)
     * @return mixed
     */
    public function accomplish()
    {
        $data = input();
        $group = Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->find();
        if (!$group) {
            return ajax_return_error('不存在或未填写信息');
        }
        if ($group['dispatch_group_status'] != 'proceed') {

            return ajax_return_error('状态冲突');
        }
        $update['dispatch_group_status'] = 'achieve';
        $update['achieve_time'] = NOW_TIME;

        $re = Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->update($update);

        $dispatch = Db::name('dispatch_traveler_group')
            ->where('id', 'not in', $data['id'])
            ->where('dispatch_group_status', 'in', 'sendorders,proceed')
            ->where('driver_user_id', $group['driver_user_id'])
            ->select();
        //释放司机
        if (!count($dispatch)) {
            Db::name('driver')->where('user_id', $group['driver_user_id'])->update(array('inservice' => false));
        }

        $date_time = date("Y-m-d H:i:s", NOW_TIME);
        set_info($group['driver_user_id'], '已经完成', "{$date_time} 你的订单已经完成，订单编号为{$data['id']},结算金额为{$group['settlement_money']}", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $data['id']));

        if ($re) {
            return ajax_return_adv('操作成功');
        } else {

            return ajax_return_error('操作失败');
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        if (!$this->request->isAjax()) {
            $group_id = input('id');
            $group = Db::name('dispatch_traveler_group')->where(array('id' => $group_id))->find();
            if ($group['is_pickup'] == '1') {
                $travelers = Db::name("order_traveler")
                    ->where('oid', $group['oid'])
                    ->select();
            } else {
                $travelers = Db::name("dispatch_traveler")->alias('dt')
                    ->join("tp_order_traveler ot", "ot.id=dt.traveler_id", "left")
                    ->where('dt.group_id', $group_id)
                    ->field('ot.*')
                    ->select();
            }
            $driver_users = Db::name('driver')->alias('d')
                ->join('tp_admin_user u', 'u.id=d.user_id', 'left')
                ->field("u.*")
                ->select();
            $this->view->assign("vo", $group);
            $this->view->assign("driver_users", $driver_users);
            $this->view->assign('travelers', $travelers);

            $car_types = Db::name('car_type')->select();
            $this->view->assign("car_types", $car_types);

            return $this->view->fetch();
        } else {
            // 启动事务
            Db::startTrans();
            try {
                $input = input();

                $input['go_date'] = strtotime($input['go_date']);
                $input['end_date'] = strtotime($input['end_date']);
                $group = $input;
                if (!empty($group['go_date']) && !empty($group['end_date']) && ($group['go_date'] > $group['end_date'])) {
                    return ajax_return_adv_error('订单的开始日期不能大于结束日期');
                }
                $group["traveler_ids"] = $input['traveler']['id'];

                //分组

                $model_group = new \app\common\model\DispatchTravelerGroup();
                $group_id = $model_group->edit_group($group);
                // 提交事务
                Db::commit();
                return ajax_return_adv();
            } catch (\Exception $e) {
                dump($e);
                // 回滚事务
                Db::rollback();
                return ajax_return_error();
            }
        }

    }

    /**
     * 复位分配状态
     * @return mixed
     */
    public function reset_group()
    {
        $group_id = input('group_id');

        $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $group_id)->find();
        if (!($dispatch_traveler_group['dispatch_group_status'] == 'undistributed' || !$dispatch_traveler_group['dispatch_group_status'])) {
            $update['dispatch_group_status'] = 'undistributed';
            $update['driver_confirm'] = false;
            $update['isreject'] = false;
            $update['dispatch_time'] = 0;
            $update['is_settlement'] = false;
            $update['settlement_time'] = 0;
            $update['settlement_time'] = 0;
            $update['driver_user_id'] = 0;
            $update['reset_time'] = NOW_TIME;
            Db::name('dispatch_traveler_group')->where('id', $group_id)->update($update);


            if ($dispatch_traveler_group['driver_user_id']) {
                //释放司机
                Db::name('driver')->where('user_id', $dispatch_traveler_group['driver_user_id'])->update(array('inservice' => false));
                $map['user_id'] = $dispatch_traveler_group['driver_user_id'];
                $map['type'] = "reset_group";
                $map['dispatch_traveler_group_id'] = $group_id;

//                Db::name('notify')->where($map)->delete();
//                $map['type'] = "dispatch_traveler_group";
//                Db::name('notify')->where($map)->delete();

                set_info($dispatch_traveler_group['driver_user_id'], '订单取消', "你的订单已被取消，订单编号{$group_id}", 'reset_group', array('dispatch_traveler_group_id' => $group_id));

                return ajax_return_adv('操作成功');

            } else {

                return ajax_return_error('未分配司导');
            }
        } else {
            return ajax_return_error('不需要复位状态');
        }
    }

    /**
     * 分配司机
     * @return mixed
     */
    public function send_driver(Request $request)
    {

        if ($request->isPost()) {
            $postData = $request->post();

            // 验证数据
            $groupId = $postData['id'];
            $driverUserId = $postData['driver_user_id'];

            if (!$groupId) {
                return ajax_return_adv_error('缺少必要的参数');
            }
            if (!$driverUserId) {
                return ajax_return_adv_error('没有选择司机');
            }

            if (isset($postData['type']) && $postData['type'] == 'pickup') {//接机订单分配
                //接机单什么时候可进行分配？
                //在订单中存在接机时间并且未分配接机时，可进行分配

                // 判断订单是否异常
                $group_order_ids = Db::name('dispatch_traveler')
                    ->where('group_id', $groupId)
                    ->column("oid");

                //查询异常订单信息
                $exceptional_orders = Db::name('exceptional_order')->where('oid', 'in', $group_order_ids)->where('solve', false)->find();
                if ($exceptional_orders) {
                    return ajax_return_error("订单id为{$exceptional_orders['oid']}的订单存在异常状态");
                }

                //查询该订单获取该订单接机信息
                $order_info = Db::name('order')->where('id', $groupId)->find();

                if (!$order_info['pick_up_time'] && $order_info['is_pick_up'] == 0) {
                    return ajax_return_adv_error("不存在该接机订单或已分配");
                }

                //查询该司机在此接机时间时是否存在派单
                $dispatchOrder = Db::name('dispatch_traveler_group')
                    ->where('dispatch_group_status', 'in', 'sendorders,proceed')
                    ->where('driver_user_id', $driverUserId)
                    ->where('go_date', '<=', $order_info['pick_up_time'])
                    ->where('end_date', '>=', $order_info['pick_up_time'])
                    ->find();

                if ($dispatchOrder) {
                    $start = empty($dispatchOrder['go_date']) ? '' : date('Y-m-d', $dispatchOrder['go_date']);
                    $end = empty($dispatchOrder['end_date']) ? '' : date('Y-m-d', $dispatchOrder['end_date']);
                    return ajax_return_adv_error("该司机在:{$start}至{$end}存在派单,派单id为:{$dispatchOrder['id']}!");
                }

                $leave = Db::name('leave')->where('user_id', $driverUserId)
                    ->where('start_time', '<=', $order_info['pick_up_time'])
                    ->where('end_time', '>=', $order_info['pick_up_time'])
                    ->find();

                // 验证当前的时间是否与司机的请假时间是否有冲突
                if ($leave) {
                    $start = empty($leave['start_time']) ? '' : date('Y-m-d', $leave['start_time']);
                    $end = empty($leave['end_time']) ? '' : date('Y-m-d', $leave['end_time']);
                    return ajax_return_adv_error("在{$start}至{$end},该司机进行请假，产生冲突!");
                }

                $order_ids = $groupId;

                //获取dispatch_id，如果不存在则添加一条
                $dispatch_id = $this->get_dispatch_id($order_ids);
                if (!$dispatch_id) {
                    $dispatch_id = Db::name("dispatch")->insertGetId(array('dispatch_status' => 'not_dispatch'));
                }

                //获取订单旅客信息
                $order_traveler_info = Db::name('order_traveler')->where('oid', $order_ids)->field('id')->select();

                //整理派车单数据
                $dispatch_traveler_group = [
                    'dispatch_id' => $dispatch_id,
                    'num' => count($order_traveler_info),
                    'driver_user_id' => $driverUserId,
                    'driver_confirm' => 0,
                    'dispatch_group_status' => 'sendorders',
                    'is_settlement' => 0,
                    'title' => '接机单：' . $order_info['title'],
                    'create_time' => time(),
                    'is_pickup' => 1,
                    'oid' => $order_info['id'],
                    'route_id' => $order_info['route_id'],
                ];

                //产生新的派车单
                $group_id = Db::name('dispatch_traveler_group')->insertGetId($dispatch_traveler_group);


                if ($group_id) {
                    //更新司机状态
                    $driver_update = Db::name("driver")->where('user_id', $driverUserId)->update(array('inservice' => 1));

                    //更新订单接机分配状态
                    $order_update = Db::name("order")->strict(false)->where('id', $order_ids)->update(array('is_deal_pick_up' => 1));

                    $map['user_id'] = $driverUserId;
                    $map['type'] = "dispatch_traveler_group";
                    $map['dispatch_traveler_group_id'] = $group_id;
                    $title = Db::name('dispatch_traveler_group')->where('id', $group_id)->value('title');
                    logs('20190218ndfghgfh', $map);
                    $re = set_info($driverUserId, '订单分配', "分配接机订单成功,您有新的订单,订单编号为:{$group_id},订单名称为:{$title}", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $group_id));
                    // --------------发送短信给司机-----------------
//                         查找该司机的手机号码
                    $mobile = Db::name('admin_user')->where('id', $driverUserId)->value('mobile');
                    if ($mobile) {
                        $ret = send_message($mobile, "分配接机订单成功,您有新的订单,订单编号为:{$group_id},订单名称为:{$title}");
                        logs('paidan', $ret);
                    }
                    return ajax_return_adv('操作成功');

                } else {

                    return ajax_return_error('未分配司导');
                }

            } else {
                //正常订单分配
                // 判断订单是否异常
                $group_order_ids = Db::name('dispatch_traveler')
                    ->where('group_id', $groupId)
                    ->column("oid");
                $exceptional_orders = Db::name('exceptional_order')->where('oid', 'in', $group_order_ids)->where('solve', false)->find();
                if ($exceptional_orders) {
                    return ajax_return_error("订单id为{$exceptional_orders['oid']}的订单存在异常状态");
                }
                // 寻找该分组数据
                $groupInfo = Db::name('dispatch_traveler_group')->where('id', $groupId)->find();
                if (!$groupInfo) {
                    return ajax_return_adv_error("不存在派单号:{$groupId}的信息!");
                }
                // 验证当前的派单与司机的进行中与派单中的派单的出发时间与结束时间是否冲突
                $date = [];
                if (!empty($groupInfo['go_date']) && !empty($groupInfo['end_date'])) {
                    $tian = round(($groupInfo['end_date'] - $groupInfo['go_date']) / 3600 / 24);
                    // 当前的入住日期
                    $check_in_date = date('Y-m-d', $groupInfo['go_date']);
                    // 把入住日期与退房日期的相差天数
                    $date = [$check_in_date];
                    logs('cha', $date);
                    for ($i = 1; $i <= $tian; $i++) {
                        array_push($date, date("Y-m-d", strtotime("+{$i} day", $groupInfo['go_date'])));//添加的
                    }
                }
                if ($date) {
                    foreach ($date as $index2 => $dateItem) {
                        $dispatchOrder = Db::name('dispatch_traveler_group')
                            ->where('dispatch_group_status', 'in', 'sendorders,proceed')
                            ->where('driver_user_id', $driverUserId)
                            ->where('go_date', '<=', strtotime($dateItem))
                            ->where('end_date', '>=', strtotime($dateItem))
                            ->find();
                        if ($dispatchOrder) {
                            $start = empty($groupInfo['go_date']) ? '' : date('Y-m-d', $groupInfo['go_date']);
                            $end = empty($groupInfo['end_date']) ? '' : date('Y-m-d', $groupInfo['end_date']);
                            return ajax_return_adv_error("派单时间:{$start}至{$end},与司机的派单id为:{$dispatchOrder['id']}的时间冲突!");
                        }
                        $leave = Db::name('leave')->where('user_id', $driverUserId)
                            ->where('start_time', '<=', $dateItem)
                            ->where('end_time', '>=', $dateItem)
                            ->find();
                        // 验证当前的时间是否与司机的请假时间是否有冲突
                        if ($leave) {
                            $start = empty($groupInfo['go_date']) ? '' : date('Y-m-d', $groupInfo['go_date']);
                            $end = empty($groupInfo['end_date']) ? '' : date('Y-m-d', $groupInfo['end_date']);
                            return ajax_return_adv_error("派单时间:{$start}至{$end},与司机的请假时间为:{$leave['start_time']}至{$leave['end_time']}，产生冲突!");
                        }
                    }
                }
                // 保存数据
                if ($groupInfo['dispatch_group_status'] == 'undistributed' || !$groupInfo['dispatch_group_status']) {
                    $update = input();
                    $update['dispatch_group_status'] = 'sendorders';
                    $update['driver_confirm'] = false;
                    $update['isreject'] = false;
                    $update['dispatch_time'] = NOW_TIME;
                    Db::name('dispatch_traveler_group')->where('id', $groupId)->update($update);
                    Db::name("driver")->where('user_id', $driverUserId)->update(array('inservice' => 1));
                    Db::name('dispatch_insurance')->strict(false)->insert(array('group_id' => $groupId, 'status' => 0));
                    if ($update['driver_user_id']) {
                        $map['user_id'] = $update['driver_user_id'];
                        $map['type'] = "dispatch_traveler_group";
                        $map['dispatch_traveler_group_id'] = $groupId;
                        $title = Db::name('dispatch_traveler_group')->where('id', $groupId)->value('title');
                        logs('20190218ndfghgfh', $map);
                        $re = set_info($driverUserId, '订单分配', "分配订单成功,您有新的订单,订单编号为:{$groupId},订单名称为:{$title}", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $groupId));
                        // --------------发送短信给司机-----------------
                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $update['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "分配订单成功,您有新的订单,订单编号为:{$groupId},订单名称为:{$title}");
                            logs('paidan', $ret);
                        }
                        return ajax_return_adv('操作成功');

                    } else {

                        return ajax_return_error('未分配司导');
                    }
                } else {
                    return ajax_return_error('已经分配');
                }
            }
        } else {
            $data = input();

            if ($data['realname']) {
                $adminUser = Db::name('admin_user')->where('realname', 'like', "%{$data['realname']}%")->select();
                if ($adminUser) {
                    $userIds = '';
                    foreach ($adminUser as $index33 => $item33) {
                        $userIds .= $item33['id'] . ',';
                    }
                    $driverUserIds = rtrim($userIds, ',');
                }
            }
            if ($data['mobile']) {
                $adminUser = Db::name('admin_user')->where('account', 'like', "%{$data['mobile']}%")->select();
                if ($adminUser) {
                    $userIds = '';
                    foreach ($adminUser as $index44 => $item44) {
                        $userIds .= $item44['id'] . ',';
                    }
                    if (empty($driverUserIds)) {
                        $driverUserIds = rtrim($userIds, ',');
                    } else {
                        $userIds = explode(',', rtrim($userIds, ','));
                        $driverUserIds = explode(',', $driverUserIds);
                        foreach ($driverUserIds as $keys => $val) {
                            if (!in_array($val, $userIds)) {
                                unset($driverUserIds[$keys]); // 删除不在这里的司机
                            }
                        }
                        $driverUserIds = empty($driverUserIds) ? '' : implode(',', $driverUserIds); // 转换成字符串
                    }
                }
            }
            if ($data['seats']) {
                $map['d.seats'] = $data['seats'];
            }
            if ($data['car_type']) {
                $map['d.car_type'] = array('like', "%{$data['car_type']}%");
            }
            if ($data['car_model']) {
                $map['d.car_model'] = array('like', "%{$data['car_model']}%");
            }
            if ($data['vehicle_level']) {
                $map['d.vehicle_level'] = array('like', "%{$data['vehicle_level']}%");
            }
            if ($data['car_brand']) {
                $map['d.car_brand'] = array('like', "%{$data['car_brand']}%");
            }
            if ($data['driver_rank_id']) {
                if ($data['driver_rank_id'] == 5) {
                    $map['d.driver_rank_id'] = 0;
                } else {
                    $map['d.driver_rank_id'] = $data['driver_rank_id'];
                }
            }
            if ($data['nationality']) {
                $map['d.nationality'] = ['like', "%{$data['nationality']}%"];
            }
            if ($data['tag']) {

                $map['d.tag'] = array('like', "%{$data['tag']}%");
            }
            $groupId = $data['group_id'];
            if (!$groupId) {
                return ajax_return_adv_error('缺少必要参数');
            }
            $map['d.ischeck'] = 1;
            $map['d.isagree'] = 1;
            $map['d.status'] = 1;
            $map['d.isdelete'] = 0;
            $map['d.inservice'] = 0; // 不在服务中
            // 查询所有不在服务的司机
            $outOfServiceDrivers = Db::name('driver')->alias('d')
                ->where($map)
                ->select();

            if ($outOfServiceDrivers) {
                $out['dispatch_group_status'] = ['in', 'sendorders,proceed'];
                foreach ($outOfServiceDrivers as $index => $outOfServiceDriver) {
                    $outData = Db::name('dispatch_traveler_group')->where($out)->where('driver_user_id', $outOfServiceDriver['user_id'])->select();
                    if (empty($outData)) {
                        $outData = [];
                    }
                    if (count($outData) >= 2) {
                        unset($outOfServiceDrivers[$index]);
                        continue;
                    }
                    $outOfServiceDrivers[$index]['dispatchOrder'] = $outData;
                    // 查找司机的用户信息
                    $driverUser = Db::name('admin_user')->where('id', $outOfServiceDriver['user_id'])->find(); // 司机用户信息
                    $outOfServiceDrivers[$index]['phone'] = empty($driverUser['mobile']) ? '用户未填手机号码' : $driverUser['mobile'];
                    $outOfServiceDrivers[$index]['realname'] = empty($driverUser['realname']) ? '用户未填姓名' : $driverUser['realname'];
                    // 整理司机的车辆信息
                    $articName = Db::name('arctic')->where('id', $outOfServiceDriver['arctic_id'])->value('name'); // 查找车型名字
                    if (!empty($articName)) {
                        $outOfServiceDrivers[$index]['arctic'] = $articName;
                    } else {
                        $outOfServiceDrivers[$index]['arctic'] = empty($outOfServiceDriver['car_type']) ? '未填写车型' : $outOfServiceDriver['car_type'];
                    }
                    $carModelName = Db::name('car_model')->where('id', $outOfServiceDriver['car_model_id'])->value('car_model'); // 查找汽车型号名字
                    if (!empty($carModelName)) {
                        $outOfServiceDrivers[$index]['car_model'] = $carModelName;
                    } else {
                        $outOfServiceDrivers[$index]['car_model'] = empty($outOfServiceDriver['car_model']) ? '未填写汽车型号' : $outOfServiceDriver['car_model'];
                    }
                    $carBrandName = Db::name('car_brand')->where('id', $outOfServiceDriver['car_brand_id'])->value('brand_name'); // 查找车辆品牌名字
                    if (!empty($carBrandName)) {
                        $outOfServiceDrivers[$index]['brand_name'] = $carBrandName;
                    } else {
                        $outOfServiceDrivers[$index]['brand_name'] = empty($outOfServiceDriver['car_brand']) ? '未填写车辆品牌' : $outOfServiceDriver['car_brand'];
                    }
                }
            }

            // 过滤不在条件的司机
            if (!empty($driverUserIds)) {
                foreach ($outOfServiceDrivers as $index77 => $outOfServiceDriver77) {
                    if (!in_array($outOfServiceDriver77['user_id'], explode(',', $driverUserIds))) {
                        unset($outOfServiceDrivers[$index77]);
                    }
                }
            }
            $map['d.inservice'] = 1; // 服务中
            // 查询所有在服务的司机
            $driverInService = Db::name('driver')->alias('d')
                ->where($map)
                ->select();
            if ($driverInService) {
                $in['dispatch_group_status'] = ['in', 'sendorders,proceed']; // 进行中或派单中
                foreach ($driverInService as $index01 => $item01) {
                    $inData = Db::name('dispatch_traveler_group')->where($in)->where('driver_user_id', $item01['user_id'])->select();
                    if (empty($inData)) {
                        $inData = [];
                    }
                    // 去掉有两个单的司机
                    if (count($inData) >= 2) {
                        unset($driverInService[$index01]);
                        continue;
                    }
                    $driverInService[$index01]['dispatchOrder'] = $inData;
                    // 查找司机的用户信息
                    $driverUser = Db::name('admin_user')->where('id', $item01['user_id'])->find(); // 司机用户信息
                    $driverInService[$index01]['phone'] = empty($driverUser['mobile']) ? '用户未填手机号码' : $driverUser['mobile'];
                    $driverInService[$index01]['realname'] = empty($driverUser['realname']) ? '用户未填姓名' : $driverUser['realname'];
                    // 整理司机的车辆信息
                    $articName = Db::name('arctic')->where('id', $item01['arctic_id'])->value('name'); // 查找车型名字
                    if (!empty($articName)) {
                        $driverInService[$index01]['arctic'] = $articName;
                    } else {
                        $driverInService[$index01]['arctic'] = empty($item01['car_type']) ? '未填写车型' : $item01['car_type'];
                    }
                    $carModelName = Db::name('car_model')->where('id', $item01['car_model_id'])->value('car_model'); // 查找汽车型号名字
                    if (!empty($carModelName)) {
                        $driverInService[$index01]['car_model'] = $carModelName;
                    } else {
                        $driverInService[$index01]['car_model'] = empty($item01['car_model']) ? '未填写汽车型号' : $item01['car_model'];
                    }
                    $carBrandName = Db::name('car_brand')->where('id', $item01['car_brand_id'])->value('brand_name'); // 查找车辆品牌名字
                    if (!empty($carBrandName)) {
                        $driverInService[$index01]['brand_name'] = $carBrandName;
                    } else {
                        $driverInService[$index01]['brand_name'] = empty($item01['car_brand']) ? '未填写车辆品牌' : $item01['car_brand'];
                    }
                }
            }
            // 过滤不在条件的司机
            if (!empty($driverUserIds)) {
                foreach ($driverInService as $index78 => $value78) {
                    if (!in_array($value78['user_id'], explode(',', $driverUserIds))) {
                        unset($driverInService[$index78]);
                    }
                }
            }
            // 查找所有司机标签
            $map_tags['isdelete'] = 0;
            $map_tags['status'] = 1;
            $driver_tags = Db::name('driver_tag')
                ->where($map_tags)
                ->select();

            if (isset($data['type']) && $data['type'] == 'pickup') {
                $this->view->assign('type', $data['type']);
            }
            // 查询派单信息
            $groupInfo = Db::name('dispatch_traveler_group')->where('id', $groupId)->find();
            // 查询所有司机的等级
            $ranks = Db::name('driver_rank')->select();
            $this->view->assign('driver_tags', $driver_tags);
            $this->view->assign('ranks', $ranks);
            $this->view->assign('outOfServiceDrivers', $outOfServiceDrivers);
            $this->view->assign('driverInService', $driverInService);
            $this->view->assign('group_id', $groupId);
            $this->view->assign('group', $groupInfo);
            return $this->view->fetch();
        }
    }

//    /**
//     * 结算
//     * @description 已结算按钮
//     * @return mixed
//     */
//    public function settlement()
//    {
//        $update=input();
//        $group_id=input('group_id');
//        $now_time = time();
//        $dispatch_traveler_group=Db::name('dispatch_traveler_group')->where('id',$group_id)->find();
//
//            if ($dispatch_traveler_group['driver_user_id']) {
//
//                $update['dispatch_group_status']='accounts';
//                $update['is_settlement']=true;
//                $update['settlement_time']=$now_time;
//                Db::name('dispatch_traveler_group')->where('id',$group_id)->update($update);
//
//                $map['user_id'] = $dispatch_traveler_group['driver_user_id'];
//                $map['type'] = "checkouted";
//                $map['dispatch_traveler_group_id'] = $group_id;
//                $notify = Db::name('notify')->where($map)->find();
//                if ($notify) {
//
//                    return ajax_return_error('已经通知过');
//                }
//                $date_time=date("Y-m-d H:i:s",$now_time);
//                set_info($dispatch_traveler_group['driver_user_id'], '已经结算',"{$date_time} 你的订单已经结算，订单编号为{$group_id},结算金额为{$dispatch_traveler_group['settlement_money']}", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $group_id));
//
//                // 增加司机的订单量
//                $driver_user_id = $dispatch_traveler_group['driver_user_id'];
//                $updateDriver = Db::name('driver')->where('user_id',$driver_user_id)->setInc('order_num'); // 订单量自增1
//                if ($updateDriver){
//                    return ajax_return_adv('操作成功');
//                }else{
//                    return ajax_return_adv_error('操作失败');
//                }
//
//
//            }else{
//
//                return ajax_return_error('未分配司导');
//            }
//
//    }
//
//    /**
//     * 拒绝结算
//     * @return mixed
//     */
//    public function reject_settlement()
//    {
//        $update=input();
//        $group_id=input('group_id');
//        $now_time = time();
//        $dispatch_traveler_group=Db::name('dispatch_traveler_group')->where('id',$group_id)->find();
//
//        if ($dispatch_traveler_group['driver_user_id']) {
//
////            $update['dispatch_group_status']='accounts';
//            $update['dispatch_group_status']='achieve';//把结算状态改为已完成状态
//            $update['is_settlement']=false;
//            $update['reject_settlement_time']=$now_time;
//            $update['is_reject_settlement']=true;
//            $update['reject_settlement_reason']="订单结算不通过";
//
//            Db::name('dispatch_traveler_group')->where('id',$group_id)->update($update);
//
//            $map['user_id'] = $dispatch_traveler_group['driver_user_id'];
//            $map['type'] = "reject_settlement";
//            $map['dispatch_traveler_group_id'] = $group_id;
//            $notify = Db::name('notify')->where($map)->find();
//            if ($notify) {
//
//                return ajax_return_error('已经通知过');
//            }
//            $date_time=date("Y-m-d H:i:s",$now_time);
//            set_info($dispatch_traveler_group['driver_user_id'], '订单结算不通过',"{$date_time} 你的订单结算不通过，订单编号为{$group_id},结算金额为{$dispatch_traveler_group['settlement_money']}", 'reject_settlement', array('dispatch_traveler_group_id' => $group_id));
//
//            return ajax_return_adv('操作成功');
//
//        }else{
//
//            return ajax_return_error('未分配司导');
//        }
//
//    }

    /**
     * 获取派遣单号id
     * @return mixed
     */
    public function get_dispatch_id($order_id)
    {
        $map['oid'] = array('in', $order_id);
        $dispatch_id = Db::name('dispatch_order')->where($map)->value('dispatch_id');
        return $dispatch_id;
    }

    /**
     * 旅客
     * @return mixed
     */
    public function traveler()
    {
        $data = input();

        if ($data['sales_id']) {
            $map['o.sales_id'] = array('in', $data['sales_id']);
        }
        if ($data['sales_id']) {
            $map['o.sales_id'] = array('in', $data['sales_id']);
        }
        if ($this->request->param("order_id")) {
            $map['o.order_id'] = array('like', "%{$this->request->param("order_id")}%");
        }
        if ($data['booking_people_name']) {
            $map['o.booking_people_name'] = array('like', "%{$data['booking_people_name']}%");
        }
        if ($data['booking_people_phone']) {
            $map['o.booking_people_phone'] = array('like', "%{$data['booking_people_phone']}%");
        }

        if ($this->request->param("name")) {
            $map['ot.name'] = array('like', "%{$this->request->param("name")}%");
        }

        if ($this->request->param("phone")) {
            $map['ot.phone'] = array('like', "%{$this->request->param("phone")}%");
        }
        if ($this->request->param("id_card")) {
            $map['ot.id_card'] = array('like', "%{$this->request->param("id_card")}%");
        }
        if ($data['sku_id']) {
            $map['o.sku_id'] = array('in', $data['sku_id']);
        }
        if ($data['order_status']) {
            $map['o.order_status'] = $data['order_status'];
        }
        if ($data['isrefund'] == '0' || $data['isrefund']) {
            $map['o.isrefund'] = $data['isrefund'];
        }
        if ($data['platform']) {
            $map['o.platform'] = $data['platform'];
        }
        $map['o.order_status'] = array('not in', array('close', 'finish'));
        if ($this->request->param("isallot")) {
            $map['ot.group_id'] = array('gt', 0);
        } elseif ($this->request->param("isallot") === "0") {
            $map['ot.group_id'] = 0;
        }
        if ($data['date1']) {
            $date1 = strtotime($data['date1']);
        }
        if ($data['date2']) {
            $date2 = strtotime($data['date2']);
        }

        if ($date1 && $date2) {
            if ($date1 < $date2) {
                $start = $date1;
                $end = $date2;
            } else {
                $start = $date2;
                $end = $date1;
            }
        } else if ($date1) {
            $start = $date1;
        } else if ($date2) {
            $start = $date2;
        }
        if ($start && $end) {
            $map['o.start_time'] = array('between', array($start, $end));
            $this->request->get(array("date1" => date("Y-m-d", $start)));
            $this->request->get(array("date2" => date("Y-m-d", $end)));
        } else if ($start) {
            //            $map['o.start_time'] = array("egt",$start);
            $map['o.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['start_time'] . " 23:59:59")]);
            $this->request->get(array("date1" => date("Y-m-d", $start)));
        }
        if ($data['ctime']) {
            $map['o.ctime'] = array("between", [strtotime($data['ctime'] . " 00:00:00"), strtotime($data['ctime'] . " 23:59:59")]);

        }

        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");
        $map['group_id'] = 0;

        $traveler_ids = $data['traveler']['id'];
        if ($traveler_ids) {
            $map['ot.id'] = array('not in', $traveler_ids);
        }

        $list = Db::name('OrderTraveler')
            ->alias("ot")
            ->join("order o", "ot.oid=o.id", 'left')
            ->where($map)
            ->order('ot.oid desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        //获取订单id
        $oids = [];
        foreach ($list as $item) {
            $oids[$item['oid']] = true;
        }
        $oids = array_keys($oids);
        $order_travelers = [];
        if ($traveler_ids) {
            $map_t['ot.id'] = array('not in', $traveler_ids);
        }

        foreach ($oids as $oid) {
            $travelers = Db::name('OrderTraveler')
                ->alias("ot")
                ->join("tp_order o", "ot.oid=o.id", 'left')
                //                ->join("tp_route r","r.id=o.route_id",'left')
                ->where('ot.oid', $oid)
                ->where('ot.group_id', 0)
                ->where($map_t)
                ->order('ot.oid desc')
                ->field("ot.*,o.title,o.start_time,o.car_form,o.booking_people_name,o.booking_people_phone,o.sales_id,o.order_id")
                ->select();
            $num = count($travelers);
            if ($num == 1) {
                $travelers[0]['show_single'] = true;
                $travelers[0]['show_mian'] = false;
                $travelers[0]['show_between'] = false;
                $travelers[0]['show_end'] = false;
                $order_travelers[] = $travelers[0];
            } else {
                foreach ($travelers as $key => $traveler) {
                    if ($key == 0) {
                        $travelers[$key]['show_single'] = false;
                        $travelers[$key]['show_mian'] = true;
                        $travelers[$key]['show_between'] = false;
                        $travelers[$key]['show_end'] = false;
                    } elseif ($key + 1 < $num) {
                        $travelers[$key]['show_single'] = false;
                        $travelers[$key]['show_mian'] = false;
                        $travelers[$key]['show_between'] = true;
                        $travelers[$key]['show_end'] = false;
                    } elseif ($key + 1 == $num) {
                        $travelers[$key]['show_single'] = false;
                        $travelers[$key]['show_mian'] = false;
                        $travelers[$key]['show_between'] = false;
                        $travelers[$key]['show_end'] = true;
                    }
                    $order_travelers[] = $travelers[$key];
                }
            }

        }

        //        dump($order_travelers);
        // 模板赋值显示
        $this->view->assign('list', $order_travelers);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 旅客信息
     * @return mixed
     */
    public function traveler_info()
    {
        $id = input('id');
        if ($id) {
            $map['id'] = array('in', $id);
            $travelers = Db::name('order_traveler')
                ->where($map)
                ->select();
            return ajax_return($travelers);
        } else {
            return ajax_return_error("缺少id参数");
        }

    }

    /**
     * 异常
     * @return mixed
     */
    public function exceptional()
    {
        $group_order_ids = Db::name('dispatch_traveler')->group('group_id')->column("oid");
        $exceptional_orders = Db::name('exceptional_order')->where('oid', 'in', $group_order_ids)->select();
        $this->view->assign('list', $exceptional_orders);
        return $this->view->fetch();
    }

    /**
     * 删除
     * @return mixed
     */
    public function delete()
    {
        // 启动事务
        Db::startTrans();
        try {
            $group_id = input('id');
            $group = Db::name('dispatch_traveler_group')->where('id', $group_id)->find();
            $order_ids = Db::name('dispatch_traveler')
                ->distinct(true)
                ->where('group_id', $group_id)
                ->column('oid');
            Db::name('order_traveler')
                ->where('group_id', $group_id)
                ->update(array('group_id' => 0));
            Db::name("driver")->where('user_id', $group['driver_user_id'])->update(array('inservice' => 0));
            Db::name("dispatch_traveler_group")->where('id', $group_id)->delete();


            $dispatch_id = $group['dispatch_id'];
            //删除原来订单分配
            //1、要删除的
            $_del_dispatch_order_ids = Db::name("dispatch_order")->where(array('dispatch_id' => $dispatch_id))->column('oid');
            //2、不可删除的
            $not_del_dispatch_order_ids = Db::name('dispatch_traveler')->where(array('dispatch_id' => $dispatch_id, 'group_id' => array('neq', $group_id)))->column('oid');
            //获取真正可删除的
            $read_del_dispatch_order_ids = [];
            foreach ($_del_dispatch_order_ids as $del_oid) {
                if (!in_array($del_oid, $not_del_dispatch_order_ids)) {
                    $read_del_dispatch_order_ids[] = $del_oid;
                }
            }
            Db::name('dispatch_order')->where(array('dispatch_id' => $dispatch_id, 'oid' => array('in', $read_del_dispatch_order_ids)))->delete();
            if (!$not_del_dispatch_order_ids) {
                Db::name('dispatch')->where(array('id' => $dispatch_id))->delete();
            }


            Db::name("dispatch_traveler")->where('group_id', $group_id)->delete();
            //更改订单状态
            $order_ids = Db::name('dispatch_traveler')->where('group_id', $group_id)->column('oid');
            $order_ids = array_merge($order_ids, $_del_dispatch_order_ids);

            $_map = [];
            $_map['id'] = array('in', $order_ids);
            Db::name('order')->where($_map)->update(array('isallot' => true, 'allot_end' => true));
            //订单里旅客是否已分配完-start
            //获取未分配完旅客的订单id
            $_map_not_allot_traveler['oid'] = array('in', $order_ids);
            $not_allot_traveler_order_id = Db::name('order_traveler')
                ->where($_map_not_allot_traveler)
                ->where(function ($query) {
                    $query->where('group_id is null')
                        ->whereOr('group_id', "=", "0");
                })
                ->column('oid');
            if ($not_allot_traveler_order_id) {
                $_map_allot_end_false['id'] = array('in', $not_allot_traveler_order_id);
                Db::name('order')->where($_map_allot_end_false)->update(array('allot_end' => false));
            }


            set_info($group['driver_user_id'], '订单取消', "你的订单已被取消，订单编号{$group_id}", 'reset_group', array('dispatch_traveler_group_id' => $group_id));
            // 提交事务
            Db::commit();
            return ajax_return_adv('删除成功');
        } catch (\Exception $e) {
            dump($e);
            // 回滚事务
            Db::rollback();
            return ajax_return_error();
        }
    }

    /**
     * 申请中止
     *
     */
    public function suspension(Request $request)
    {
        if ($request->isPost()) {//post请求
            $post = $request->post();
            $group_id = $post['group_id'];
            $group = Db::name('dispatch_traveler_group')->where('id', $group_id)->find();
            $driverName = Db::name('admin_user')->where('id', $group['driver_user_id'])->value('realname');
            if (!$group) {
                return ajax_return_adv_error('不存在该分组信息');
            } elseif ($group['dispatch_group_status'] != 'proceed') {
                return ajax_return_adv_error('该订单不能申请中止请求!');
            }
            $insert = [
                'suspend_reason' => $post['rejection_reason'],
                'suspension_time' => time(),
                'is_suspend' => 2,//申请
                'old_driver_user_id' => $group['driver_user_id'],
                'old_driver_user_name' => $driverName,
            ];
            //添加数据
            $up = Db::name('dispatch_traveler_group')->where('id', $group_id)->strict(false)->update($insert);
            if ($up) {
                // 向司机发送中止原因
                $content = $post['rejection_reason'];
                set_info($group['driver_user_id'], '中止订单信息', $content, 'system_ordinary_info', $post);
                return ajax_return_adv('申请中止成功');
            } else {
                return ajax_return_adv_error('申请中止失败');
            }
        } else {
            $data = input();
            $group_id = $data['group_id'];
            //查询该分组数据
            $group = Db::name('dispatch_traveler_group')->where('id', $group_id)->find();
            //查询司机的用户名
            $driverUserInfo = Db::name('admin_user')->where('id', $group['driver_user_id'])->find();
            if (!$driverUserInfo) {
                return ajax_return_adv_error('不存在该司机用户信息');
            }
            $this->view->assign('group_id', $group_id);
            $this->view->assign('driverUserInfo', $driverUserInfo);
            return $this->view->fetch();
        }
    }

    /**
     * 重新分配
     *
     */
    public function reallocates()
    {
        $input = input();
        $group_id = $input['group_id'];
        logs('20190307data', input());
        if (!$this->request->isAjax()) {
            if ($input['realname']) {
                $map['u.realname'] = array('like', "%{$input['realname']}%");
            }
            if ($input['mobile']) {
                $map['u.account'] = array('like', "%{$input['mobile']}%");
            }
            if ($input['seats']) {
                $map['d.seats'] = $input['seats'];
            }
            if ($input['car_type']) {
                $map['d.car_type'] = array('like', "%{$input['car_type']}%");
            }
            if ($input['car_brand']) {
                $map['d.car_brand'] = array('like', "%{$input['car_brand']}%");
            }
            if ($input['car_model']) {
                $map['d.car_model'] = array('like', "%{$input['car_model']}%");
            }
            if ($input['driver_rank_id']) {
                $map['d.driver_rank_id'] = $input['driver_rank_id'];
            }
            if ($input['tag']) {
                $map['d.tag'] = array('like', "%{$input['tag']}%");
            }
            if ($input['nationality']) {
                $map['d.nationality'] = ['like', "%{$input['nationality']}%"];
            }
            $map['d.inservice'] = false;
            $group = Db::name('dispatch_traveler_group')->where(array('id' => $group_id))->find();
            $driver_users = Db::name('driver')->alias('d')
                ->join('tp_admin_user u', 'u.id=d.user_id', 'left')
                ->join("tp_driver_rank r", "r.id=d.driver_rank_id", "left")
                ->where('isagree', 1)
                ->where($map)
                ->where('u.id', '<>', $group['driver_user_id'])
                ->field("u.*,d.*,r.name as r_name,d.nationality")
                ->select();
            $map['d.inservice'] = 1;
            //服务中的司机
            $drivers_in_service = Db::name('driver')->alias('d')
                ->join('tp_admin_user u', 'u.id=d.user_id', 'left')
                ->join("tp_driver_rank r", "r.id=d.driver_rank_id", "left")
                ->where('isagree', 1)
                ->where($map)
                ->where('u.id', '<>', $group['driver_user_id'])//不能存在申请中止的司机
                ->field("u.*,d.*,r.name as r_name,d.nationality")
                ->select();
            //司机已经有两个单的过滤掉
            $driverUserIds = '';//服务中司机id
            foreach ($drivers_in_service as $disk => $disv) {
                $driverUserIds .= $disv['user_id'] . ',';
            }
            $driverUserIds = rtrim($driverUserIds, ',');
            $driverUsers = Db::name('dispatch_traveler_group')->where('driver_user_id', 'in', $driverUserIds)
                ->field('id,dispatch_id,driver_user_id,go_date,end_date,dispatch_group_status')->select();
            $sql = Db::name('dispatch_traveler_group')->where('driver_user_id', 'in', $driverUserIds)
                ->field('id,dispatch_id,driver_user_id,go_date,end_date,dispatch_group_status')->fetchSql(true)->select();
            //去掉未分配、已完成、已结算
            foreach ($driverUsers as $dik => $div) {
                if ($div['dispatch_group_status'] == 'undistributed' || $div['dispatch_group_status'] == 'accounts' || $div['dispatch_group_status'] == 'achieve') {
                    unset($driverUsers[$dik]);
                }
            }
            //
            $driverUserIds = explode(',', $driverUserIds);
            $driverArr = [];
            foreach ($driverUsers as $duk => $duv) {
                if (in_array($duv['driver_user_id'], $driverUserIds)) {
                    $driverArr[$duv['driver_user_id']][] = $duv;
                }
            }
            foreach ($drivers_in_service as $kkk => $vvv) {
                //去掉已有两个单的司机
                foreach ($driverArr as $dak => $dav) {
                    $davCount = count($dav);
                    if ($vvv['user_id'] == $dak && $davCount >= 2) {
                        unset($drivers_in_service[$kkk]);
                    } elseif ($vvv['user_id'] == $dak && empty($dav[0]['end_date'])) {
                        //去掉司机上个订单没有结束时间
                        unset($drivers_in_service[$kkk]);
                    } elseif ($vvv['user_id'] == $dak && $dav[0]['end_date'] > $group['go_date']) {
                        //去掉结束时间高于分配订单的出发时间
                        unset($drivers_in_service[$kkk]);
                    }
                }
            }
            $map_tags['isdelete'] = 0;
            $map_tags['status'] = 1;
            $driver_tags = Db::name('driver_tag')
                ->where($map_tags)
                ->select();
            $this->view->assign('driver_tags', $driver_tags);
            $ranks = Db::name('driver_rank')->select();
            $this->view->assign('ranks', $ranks);
            $this->view->assign('group_id', $group_id);
            $this->view->assign("driver_users", $driver_users);
            $this->view->assign("drivers_in_service", $drivers_in_service);
            $this->view->assign('vo', $group);
            return $this->view->fetch();
        }
        //判断订单是否异常
        $group_order_ids = Db::name('dispatch_traveler')
            ->where('group_id', $group_id)
            ->column("oid");
        $exceptional_orders = Db::name('exceptional_order')->where('oid', 'in', $group_order_ids)->where('solve', false)->find();
        if ($exceptional_orders) {
            return ajax_return_error("订单id为{$exceptional_orders['oid']}的订单存在异常状态");
        }
        if (!input('driver_user_id')) {
            return ajax_return_adv_error('没有选择司机');
        }
        $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $group_id)->find();//查找分组订单数据
        $now_time = time();
        //开始时间不能小于分配时间
        if ($now_time > $dispatch_traveler_group['go_date']) {
            return ajax_return_adv_error('重新分配的旅游开始日期不能低于分配的时间,请去编辑重新更改id为' . $group_id . '的开始日期和结束日期');
        }


        //判断司机是否已经在服务
        $driver = Db::name("driver")->where('user_id', $input['driver_user_id'])->find();
        if ($driver['inservice']) {
            //查找司机的订单
            //派单或者进行中
            $driverInfo = Db::name('dispatch_traveler_group')
                ->where('driver_user_id', $input['driver_user_id'])
                ->order('id', 'desc')->select();//找该司机最后的分配订单
            foreach ($driverInfo as $dik => $div) {
                if ($div['dispatch_group_status'] == 'undistributed' || $div['dispatch_group_status'] == 'accounts' || $div['dispatch_group_status'] == 'achieve') {
                    unset($driverInfo[$dik]);
                }
            }
            $driverInfo = array_values($driverInfo);
            $count = count($driverInfo);//统计当前司机有几个单
            if ($count >= 2) {
                return ajax_return_error("用户id为{$input['driver_user_id']}的司机已经分配2个单");
            }
            //寻找该司机的前一单
            $driver_final_order = $driverInfo[0];
            if (empty($driver_final_order['end_date'])) {
                // 查找司机用户ming
                $userName = Db::name('admin_user')->where('id', $input['driver_user_id'])->value('realname');
                return ajax_return_error("用户id为{$input['driver_user_id']}的{$userName}司机,他的派单id为{$driver_final_order['id']}的订单没有结束日期,不能进行比较派单");
            }
            //寻找该分组的
            $undistributed = Db::name('dispatch_traveler_group')
                ->where('id', $group_id)->where('dispatch_group_status', 'proceed')->find();
            if ($undistributed['go_date'] <= $driver_final_order['end_date']) {
                return ajax_return_error("用户id为{$input['driver_user_id']}的司机不能派单,原因是上一个订单的结束时间与与本次订单的开始时间有冲突");
            }
        }
        if ($dispatch_traveler_group['dispatch_group_status'] == 'proceed' || !$dispatch_traveler_group['dispatch_group_status']) {
            $update = input();
            //把原来数据移动到tp_reverse表
            $insertReverse = $dispatch_traveler_group;
            $insertReverse['end_date'] = time();
            unset($insertReverse['id']);
            $reverse_id = Db::name('reverse')->strict(false)->insertGetId($insertReverse);//中途换车表
            if ($dispatch_traveler_group['reverse_id']) {
                $reverse_ids = $dispatch_traveler_group['reverse_id'] . ',' . $reverse_id;
                $up = Db::name('dispatch_traveler_group')->where('id', $group_id)->update(['reverse_id' => $reverse_ids]);
            } else {
                $up = Db::name('dispatch_traveler_group')->where('id', $group_id)->update(['reverse_id' => $reverse_id]);
            }
            //把原司机有服务状态转换成未服务
            Db::name('driver')->where('user_id', $dispatch_traveler_group['driver_user_id'])->update(['inservice' => 0]);
            //清空旧司机的数据
            $insert = [
                'old_driver_user_id' => '',
                'old_driver_user_name' => '',
                'suspend_reason' => '',
                'is_suspend' => 1,
                'suspension_time' => '',
            ];
            $up = Db::name('dispatch_traveler_group')->where('id', $group_id)->strict(false)->update($insert);
            logs('up20190124', $up);
            $update['dispatch_group_status'] = 'proceed';//进行中
            $update['driver_confirm'] = false;
            $update['isreject'] = false;//是否确认
            $update['dispatch_time'] = NOW_TIME;
            Db::name('dispatch_traveler_group')->where('id', $group_id)->update($update);
            Db::name("driver")->where('user_id', $input['driver_user_id'])->update(array('inservice' => 1));
            if ($update['driver_user_id']) {
                $map['user_id'] = $update['driver_user_id'];
                $map['type'] = "dispatch_traveler_group";
                $map['dispatch_traveler_group_id'] = $group_id;

                // 同步住宿派单,查询最后的派单
                $portion_id = Db::name('portion_traveler')->where('group_id', $group_id)->order('id', 'desc')->value('id');
                $portion_traveler_num = Db::name('portion_traveler')->where('id', $portion_id)->value('number_of_guests');
                logs('num', $portion_traveler_num);
                // 从派单中获取旅客住宿的个数
                $groups = Db::name('order_traveler')->where('group_id', $group_id)->where('isaccommodation', '包含住宿')->select();
                if ($portion_traveler_num != count($groups)) {
                    // 司机接受派单，同步住宿派单
                    // 从订单旅客表获取派单旅客数据,并且有住宿要求的旅客
                    $groupTravel = Db::name('order_traveler')->where('group_id', $group_id)->where('isaccommodation', '包含住宿')->select();
                    //  查询派单数据
                    $groupInfo = Db::name('dispatch_traveler_group')->where('id', $group_id)->find();
                    // 查找司机信息
                    $driver = Db::name('driver')->where('user_id', $groupInfo['driver_user_id'])->find();
                    if ($groupTravel) {
                        // 同步住宿派单
                        $insert = [
                            'driver_id' => $driver['id'],
                            'driver_user_id' => $groupInfo['driver_user_id'],
                            'number_of_guests' => count($groupTravel),
                            'departure_date' => $groupInfo['go_date'],
                            'group_id' => $group_id,
                            'car_form' => $groupInfo['car_form'],
                            'create_time' => time(),
                        ];
                        // 添加到表里
                        $addId = Db::name('portion_traveler')->strict(false)->insertGetId($insert);
                        logs('zhongtuhuanchepaidan', $addId);
                    }
                } else {
                    // 客人没有变动,发送该派单的住宿旅客信息给旅客
                    $content = Db::name('notify')->where('user_id', $dispatch_traveler_group['driver_user_id'])
                        ->where('type', 'system_ordinary_info')
                        ->where('dispatch_traveler_group_id', $group_id)->order('id', 'desc')->value('content');
                    logs('content', $content);
                    // 添加短信内容
                    $sendMsg = [
                        'user_id' => $update['driver_user_id'],
                        'title' => '旅客住宿安排',
                        'content' => $content,
                        'create_time' => NOW_TIME,
                        'type' => 'system_ordinary_info',
                        'dispatch_traveler_group_id' => $group_id,
                    ];
                    Db::name('notify')->strict(false)->insert($sendMsg);
                    umeng_send($update['driver_user_id'], '旅客住宿安排', $content);
                }


                set_info($input['driver_user_id'], '重新分配订单', '分配成功，你有新的订单', 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $group_id));
                set_info($dispatch_traveler_group['driver_user_id'], '取消订单成功', '申请中止订单成功', 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $group_id));


                // --------------发送短信给司机-----------------
                // 查找该司机的手机号码
                $new_mobile = Db::name('admin_user')->where('id', $update['driver_user_id'])->value('mobile');
                $old_mobile = Db::name('admin_user')->where('id', $dispatch_traveler_group['old_driver_user_id'])->value('mobile');
                if ($new_mobile & $old_mobile) {
                    $ret = send_message($new_mobile, "分配订单成功,您有新的订单,订单编号为:{$group_id}");
                    array_push($ret, '分配');
                    $ret = send_message($old_mobile, "申请中止订单成功,订单编号为:{$group_id}");
                    array_push($ret, '中止');
                    logs('paidan', $ret);
                } elseif ($new_mobile) {
                    $ret = send_message($new_mobile, "分配订单成功,您有新的订单,订单编号为:{$group_id}");
                    array_push($ret, '分配');
                    logs('paidan', $ret);
                } elseif ($old_mobile) {
                    $ret = send_message($old_mobile, "申请中止订单成功,订单编号为:{$group_id}");
                    array_push($ret, '中止');
                    logs('paidan', $ret);
                }

                return ajax_return_adv('操作成功');

            } else {

                return ajax_return_error('未分配司导');
            }
        } else {
            return ajax_return_error('已经分配');
        }
    }

    /**
     * 重新派单（重新分配司机）
     * @param int id 分组id
     * @param int driver_user_id 司机用户id
     */
    public function reallocate(Request $request)
    {
        $nowTime = date('Y-m-d', time());
        if ($request->isPost()) {
            $postData = $request->post();
            // 验证数据
            $groupId = $postData['id'];
            $driverUserId = $postData['driver_user_id'];
            if (!$groupId) {
                return ajax_return_adv_error('缺少参数');
            }
            if (!$driverUserId) {
                return ajax_return_adv_error('未选择司机');
            }
            // 查找该派单的信息
            $groupInfo = Db::name('dispatch_traveler_group')->where('id', $groupId)->find();
            if (!$groupInfo) {
                return ajax_return_adv_error('不存在该派单信息!');
            }
//            elseif ($groupInfo['dispatch_group_status'] != 'undistributed') {
//                return ajax_return_adv_error('该派车单当前状态不为未分配，不可进行分配操作');
//            }
            // 重新派车的开始时间不能小于当前分配时间
//            if (date('Y-m-d', $groupInfo['go_date']) < $nowTime) {
//                return ajax_return_adv_error('重新派车的派单的出发时间小于当前的分配时间，请更改派单的出发时间!');
//            }
            // 判断订单是否异常，异常订单表有改订单的记录
            $oid = Db::name('order_traveler')->where('group_id', $groupId)->value('oid'); // 获取订单id
            $exceptionalOrder = Db::name('exceptional_order')->where('oid', 'in', $oid)->where('solve', 0)->find(); // 异常订单
            if ($exceptionalOrder) {
                return ajax_return_adv_error("订单id为:{$oid}存在异常状态");
            }
            // 获取司机的信息
            $driverUserInfo = Db::name('driver')->where('user_id', $driverUserId)->find();
            if (!$driverUserInfo) {
                return ajax_return_adv_error("用户id为:{$driverUserId}的司机信息缺失!");
            }
            if (empty($groupInfo['end_date']) || empty($groupInfo['go_date'])) {
                return ajax_return_adv_error("该派车单的出发时间或者结束时间为空，不能对比!");
            }
            // 检验当前司机的请假时间是否与派单的时间存在冲突
            // 检验当前的派单是否与司机的已有的进行中、已派单的是否冲突
            $tian = round(($groupInfo['end_date'] - $groupInfo['go_date']) / 3600 / 24);
            // 把入住日期与退房日期的相差天数
            $start_time = date('Y-m-d', $groupInfo['go_date']);
            $end_time = date('Y-m-d', $groupInfo['end_date']);
            $groupDate = [$start_time];
            for ($i = 1; $i <= $tian; $i++) {
                array_push($groupDate, date("Y-m-d", strtotime("+{$i} day", $groupInfo['go_date'])));//添加的
            }
            $map['dispatch_group_status'] = ['in', 'undistributed'];
            $map['driver_user_id'] = $driverUserId;
            $dispatchOrder = Db::name('dispatch_traveler_group')->where($map)->select();
            foreach ($groupDate as $item) {
                $leave = Db::name('leave')
                    ->where('start_time', '<=', $item)
                    ->where('end_time', '>=', $item)
                    ->where('user_id', $driverUserId)
                    ->where('isagreee', 1)
                    ->where('leave_status', 'agree')->find();
                if ($leave) {
                    return ajax_return_adv_error("该派单的时间为:{$start_time}至{$end_time},与司机的请假时间:{$leave['start_time']}至{$leave['end_time']},产生冲突");
                }
                if ($dispatchOrder) {
                    foreach ($dispatchOrder as $index => $item) {
                        if (empty($item['end_date'])) {
                            return ajax_return_adv_error("用户id为:{$driverUserId}的司机,他id为{$item['id']}的派单的结束时间不存在,不能进行派单比较!");
                        }
                        // 计算司机该派单的结束时间与开始时间
                        $itemTian = round(($item['end_date'] - $item['go_date']) / 3600 / 24);
                        // 相差天数
                        $start_time = date('Y-m-d', $groupInfo['go_date']);
                        $end_time = date('Y-m-d', $groupInfo['end_date']);
                        $go_date = date('Y-m-d', $item['go_date']);
                        $end_date = date('Y-m-d', $item['end_date']);
                        $itemDate = [$go_date];
                        for ($i = 1; $i <= $itemTian; $i++) {
                            array_push($itemDate, date("Y-m-d", strtotime("+{$i} day", $item['go_date'])));//添加的
                        }
                        foreach ($itemDate as $vo) {
                            if (in_array($vo, $groupDate)) {
                                return ajax_return_adv_error("该派单的时间为:{$start_time}至{$end_time},与司机id为{$item['id']}的派单时间:{$go_date}至{$end_date},产生冲突");
                            }
                        }
                    }
                }
            }
            // 处理分配司机派单
            $dispatchGroupInfo = Db::name('dispatch_traveler_group')->where('id', $groupId)->where('dispatch_group_status', 'undistributed')->find();
            if (!$dispatchGroupInfo['dispatch_group_status'] || $dispatchGroupInfo['dispatch_group_status'] == 'undistributed') {
                $oldData = $dispatchGroupInfo; // 保存旧的派单数据
                $oldData['end_date'] = time();
                unset($oldData['id']);
                // 添加该派单的中途换车数据，并获取添加的中途换车id
                $reverse_id = Db::name('reverse')->strict(false)->insertGetId($oldData);
                // 更换原分组的换车id
                if ($dispatchGroupInfo['reverse_id']) {
                    $reverse_ids = $dispatchGroupInfo['reverse_id'] . ',' . $reverse_id;
                    $up = Db::name('dispatch_traveler_group')->where('id', $groupId)->update(['reverse_id' => $reverse_ids]);
                } else {
                    $up = Db::name('dispatch_traveler_group')->where('id', $groupId)->update(['reverse_id' => $reverse_id]);
                }
                //检测原司机是否有新的派单，没有就恢复未服务状态
                $oldDriverOrder = Db::name('dispatch_traveler_group')->where('id', 'not in', $groupId)
                    ->where('dispatch_group_status', 'in', 'undistributed')
                    ->where('driver_user_id', $dispatchGroupInfo['driver_user_id'])
                    ->count();
                if (!$oldDriverOrder) {
                    //检测原司机是否有新的派单，没有就恢复未服务状态
                    Db::name('driver')->where('user_id', $dispatchGroupInfo['driver_user_id'])->update(['inservice' => 0]);
                }
                //清空旧司机的数据
                $insert = [
                    'old_driver_user_id' => '',
                    'old_driver_user_name' => '',
                    'suspend_reason' => '',
                    'is_suspend' => 1,
                    'suspension_time' => '',
                ];
                $up = Db::name('dispatch_traveler_group')->where('id', $groupId)->strict(false)->update($insert);
                logs('up2019012477777', $up);
                $update['driver_user_id'] = $driverUserId;
                $update['dispatch_group_status'] = 'sendorders';//进行中
                $update['driver_confirm'] = false;
                $update['isreject'] = false;//是否确认
                $update['dispatch_time'] = NOW_TIME;
                Db::name('dispatch_traveler_group')->where('id', $groupId)->strict(false)->update($update);
                Db::name("driver")->where('user_id', $driverUserId)->update(array('inservice' => 1));
                if ($driverUserId) {
                    // 同步住宿派单,查询最后的派单
                    $portion_id = Db::name('portion_traveler')->where('group_id', $groupId)->order('id', 'desc')->value('id');
                    $portion_traveler_num = Db::name('portion_traveler')->where('id', $portion_id)->value('number_of_guests');
                    logs('num', $portion_traveler_num);
                    // 从派单中获取旅客住宿的个数
                    $groups = Db::name('order_traveler')->where('group_id', $groupId)->where('isaccommodation', '包含住宿')->select();
                    if ($portion_traveler_num != count($groups)) {
                        // 司机接受派单，同步住宿派单
                        // 从订单旅客表获取派单旅客数据,并且有住宿要求的旅客
                        $groupTravel = Db::name('order_traveler')->where('group_id', $groupId)->where('isaccommodation', '包含住宿')->select();
                        //  查询派单数据
                        $groupInfo = Db::name('dispatch_traveler_group')->where('id', $groupId)->find();
                        // 查找司机信息
                        $driver = Db::name('driver')->where('user_id', $groupInfo['driver_user_id'])->find();
                        if ($groupTravel) {
                            // 同步住宿派单
//                            $insert = [
//                                'driver_id' => $driver['id'],
//                                'driver_user_id' => $groupInfo['driver_user_id'],
//                                'number_of_guests' => count($groupTravel),
//                                'departure_date' => $groupInfo['go_date'],
//                                'group_id' => $groupId,
//                                'car_form' => $groupInfo['car_form'],
//                                'create_time' => time(),
//                            ];
//                            // 添加到表里
//                            $addId = Db::name('portion_traveler')->strict(false)->insertGetId($insert);
//                            logs('zhongtuhuanchepaidan', $addId);
                        }
                    } elseif ($portion_traveler_num == count($groups)) {
                        // 客人没有变动,发送该派单的住宿旅客信息给旅客
                        $content = Db::name('notify')->where('user_id', $dispatchGroupInfo['driver_user_id'])
                            ->where('type', 'system_ordinary_info')
                            ->where('dispatch_traveler_group_id', $groupId)->order('id', 'desc')->value('content');
                        logs('content', $content);
                        if (empty($content)) {
                            $content = '该派单的住宿旅客还没有分配住宿';
                        }
                        // 添加短信内容
                        $sendMsg = [
                            'user_id' => $driverUserId,
                            'title' => '旅客住宿安排',
                            'content' => $content,
                            'create_time' => NOW_TIME,
                            'type' => 'system_ordinary_info',
                            'dispatch_traveler_group_id' => $groupId,
                        ];
                        Db::name('notify')->strict(false)->insert($sendMsg);
                        umeng_send($driverUserId, '旅客住宿安排', $content);
                    }
                    // 向司机app发送消息
                    set_info($driverUserId, '重新分配订单', "分配成功，你有新的订单，订单编号为:{$groupId},订单标题为:{$groupInfo['title']}", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $groupId));
                    set_info($dispatchGroupInfo['driver_user_id'], '取消订单成功', "您申请中止的编号为:{$groupId},标题为:{$groupInfo['title']}的派单已经处理", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $groupId));
                    //------------把派单的结果以短信的形式发送到司机的手机上面---------------
                    $new_mobile = Db::name('admin_user')->where('id', $driverUserId)->value('mobile');
                    $old_mobile = Db::name('admin_user')->where('id', $dispatchGroupInfo['old_driver_user_id'])->value('mobile');
                    if ($new_mobile & $old_mobile) {
                        $ret = send_message($new_mobile, "分配订单成功,您有新的订单,订单编号为:{$groupId}");
                        array_push($ret, '分配');
                        $ret = send_message($old_mobile, "申请中止订单成功,订单编号为:{$groupId}");
                        array_push($ret, '中止');
                        logs('paidan', $ret);
                    } elseif ($new_mobile) {
                        $ret = send_message($new_mobile, "分配订单成功,您有新的订单,订单编号为:{$groupId}");
                        array_push($ret, '分配');
                        logs('paidan', $ret);
                    } elseif ($old_mobile) {
                        $ret = send_message($old_mobile, "申请中止订单成功,订单编号为:{$groupId}");
                        array_push($ret, '中止');
                        logs('paidan', $ret);
                    }
                    $this->accept(['group_id'=>$groupId]);
                    return ajax_return_adv('操作成功!');
                } else {
                    return ajax_return_adv_error("未选择司机");
                }
            } else {
                return ajax_return_adv_error('该派单已经处理！');
            }
        } else {
            $data = input();
            if ($data['realname']) {
                $adminUser = Db::name('admin_user')->where('realname', 'like', "%{$data['realname']}%")->select();
                if ($adminUser) {
                    $userIds = '';
                    foreach ($adminUser as $index33 => $item33) {
                        $userIds .= $item33['id'] . ',';
                    }
                    $driverUserIds = rtrim($userIds, ',');
                }
            }
            if ($data['mobile']) {
                $adminUser = Db::name('admin_user')->where('account', 'like', "%{$data['mobile']}%")->select();
                if ($adminUser) {
                    $userIds = '';
                    foreach ($adminUser as $index44 => $item44) {
                        $userIds .= $item44['id'] . ',';
                    }
                    if (empty($driverUserIds)) {
                        $driverUserIds = rtrim($userIds, ',');
                    } else {
                        $userIds = explode(',', rtrim($userIds, ','));
                        $driverUserIds = explode(',', $driverUserIds);
                        foreach ($driverUserIds as $keys => $val) {
                            if (!in_array($val, $userIds)) {
                                unset($driverUserIds[$keys]); // 删除不在这里的司机
                            }
                        }
                        $driverUserIds = empty($driverUserIds) ? '' : implode(',', $driverUserIds); // 转换成字符串
                    }
                }
            }
            if ($data['seats']) {
                $map['d.seats'] = $data['seats'];
            }
            if ($data['car_type']) {
                $map['d.car_type'] = array('like', "%{$data['car_type']}%");
            }
            if ($data['car_model']) {
                $map['d.car_model'] = array('like', "%{$data['car_model']}%");
            }
            if ($data['car_brand']) {
                $map['d.car_brand'] = array('like', "%{$data['car_brand']}%");
            }
            if ($data['driver_rank_id']) {
                if ($data['driver_rank_id'] == 5) {
                    $map['d.driver_rank_id'] = 0;
                } else {
                    $map['d.driver_rank_id'] = $data['driver_rank_id'];
                }
            }
            if ($data['nationality']) {
                $map['d.nationality'] = ['like', "%{$data['nationality']}%"];
            }
            if ($data['tag']) {
                $map['d.tag'] = array('like', "%{$data['tag']}%");
            }
            $groupId = $data['group_id'];
            if (!$groupId) {
                return ajax_return_adv_error('缺少必要参数');
            }
            $map['d.ischeck'] = 1;
            $map['d.isagree'] = 1;
            $map['d.status'] = 1;
            $map['d.isdelete'] = 0;
            $map['d.inservice'] = 0; // 不在服务中
            // 查询派单信息
            $groupInfo = Db::name('dispatch_traveler_group')->where('id', $groupId)->find();
            // 计算出天数
            $groupDate = []; // 派单的天数
            if (!empty($groupInfo['go_date']) && !empty($groupInfo['end_date'])) {
                $tian = round(($groupInfo['end_date'] - $groupInfo['go_date']) / 3600 / 24);
                // 把入住日期与退房日期的相差天数
                $start_time = date('Y-m-d', $groupInfo['go_date']);
                $groupDate = [$start_time];
                for ($i = 1; $i <= $tian; $i++) {
                    array_push($groupDate, date("Y-m-d", strtotime("+{$i} day", $groupInfo['go_date'])));//添加的
                }
            }
            // 查询所有不在服务的司机
            $outOfServiceDrivers = Db::name('driver')->alias('d')
                ->where($map)
                ->select();
            if ($outOfServiceDrivers) {
                $out['dispatch_group_status'] = ['in', 'sendorders,proceed'];
                foreach ($outOfServiceDrivers as $index => $outOfServiceDriver) {
                    $outData = Db::name('dispatch_traveler_group')->where($out)->where('driver_user_id', $outOfServiceDriver['user_id'])->select();
                    if (empty($outData)) {
                        $outData = [];
                    } else {
                        // 过滤掉司机结束时间大于当前的派单的开始时间
                        foreach ($outData as $index06 => $outDatum) {
                            if (empty($outDatum['go_date']) || empty($outDatum['end_date'])) {
                                unset($outOfServiceDrivers[$index]);
                                continue 2;
                            }
                            // 计算日期数组
                            $outTian = round(($outDatum['end_date'] - $outDatum['go_date']) / 3600 / 24);
                            // 把入住日期与退房日期的相差天数
                            $start_time = date('Y-m-d', $outDatum['go_date']);
                            $outDate = [$start_time];
                            for ($i = 1; $i <= $outTian; $i++) {
                                array_push($outDate, date("Y-m-d", strtotime("+{$i} day", $outDatum['go_date'])));//添加的
                            }
                            if ($outDate && !empty($groupDate)) {
                                foreach ($outDate as $item) {
                                    if (in_array($item, $groupDate)) {
                                        unset($outOfServiceDrivers[$index]);
                                        continue 3;
                                    }
                                }
                            }
                        }
                    }
                    if (count($outData) >= 2) {
                        unset($outOfServiceDrivers[$index]);
                        continue;
                    }
                    $outOfServiceDrivers[$index]['dispatchOrder'] = $outData;
                    // 查找司机的用户信息
                    $driverUser = Db::name('admin_user')->where('id', $outOfServiceDriver['user_id'])->find(); // 司机用户信息
                    $outOfServiceDrivers[$index]['phone'] = empty($driverUser['mobile']) ? '用户为填手机号码' : $driverUser['mobile'];
                    $outOfServiceDrivers[$index]['realname'] = empty($driverUser['realname']) ? '用户为填姓名' : $driverUser['realname'];
                    // 整理司机的车辆信息
                    $articName = Db::name('arctic')->where('id', $outOfServiceDriver['arctic_id'])->value('name'); // 查找车型名字
                    if (!empty($articName)) {
                        $outOfServiceDrivers[$index]['arctic'] = $articName;
                    } else {
                        $outOfServiceDrivers[$index]['arctic'] = empty($outOfServiceDriver['car_type']) ? '未填写车型' : $outOfServiceDriver['car_type'];
                    }
                    $carModelName = Db::name('car_model')->where('id', $outOfServiceDriver['car_model_id'])->value('car_model'); // 查找汽车型号名字
                    if (!empty($carModelName)) {
                        $outOfServiceDrivers[$index]['car_model'] = $carModelName;
                    } else {
                        $outOfServiceDrivers[$index]['car_model'] = empty($outOfServiceDriver['car_model']) ? '未填写汽车型号' : $outOfServiceDriver['car_model'];
                    }
                    $carBrandName = Db::name('car_brand')->where('id', $outOfServiceDriver['car_brand_id'])->value('brand_name'); // 查找车辆品牌名字
                    if (!empty($carBrandName)) {
                        $outOfServiceDrivers[$index]['brand_name'] = $carBrandName;
                    } else {
                        $outOfServiceDrivers[$index]['brand_name'] = empty($outOfServiceDriver['car_brand']) ? '未填写车辆品牌' : $outOfServiceDriver['car_brand'];
                    }
                }
            }
            // 过滤不在条件的司机
            if (!empty($driverUserIds)) {
                foreach ($outOfServiceDrivers as $index77 => $outOfServiceDriver77) {
                    if (!in_array($outOfServiceDriver77['user_id'], explode(',', $driverUserIds))) {
                        unset($outOfServiceDrivers[$index77]);
                    }
                }
            }
            $map['d.inservice'] = 1; // 服务中
            // 查询所有在服务的司机
            $driverInService = Db::name('driver')->alias('d')
                ->where($map)
                ->select();
            if ($driverInService) {
                $in['dispatch_group_status'] = ['in', 'sendorders,proceed']; // 进行中或派单中
                foreach ($driverInService as $index01 => $item01) {
                    $inData = Db::name('dispatch_traveler_group')->where($in)->where('driver_user_id', $item01['user_id'])->select();
                    if (empty($inData)) {
                        $inData = [];
                    } else {
                        // 过滤掉司机结束时间大于当前的派单的开始时间
                        foreach ($inData as $index088 => $inDatum) {
                            if (empty($inDatum['go_date']) || empty($inDatum['end_date'])) {
                                unset($driverInService[$index01]);
                                continue 2;
                            }
                            // 计算日期数组
                            $inTian = round(($inDatum['end_date'] - $inDatum['go_date']) / 3600 / 24);
                            // 把入住日期与退房日期的相差天数
                            $start_time = date('Y-m-d', $inDatum['go_date']);
                            $inDate = [$start_time];
                            for ($i = 1; $i <= $inTian; $i++) {
                                array_push($inDate, date("Y-m-d", strtotime("+{$i} day", $inDatum['go_date'])));//添加的
                            }
                            if ($inDate && !empty($groupDate)) {
                                foreach ($inDate as $item) {
                                    if (in_array($item, $groupDate)) {
                                        unset($driverInService[$index01]);
                                        continue 3;
                                    }
                                }
                            }
                        }
                    }
                    // 去掉有两个单的司机
                    if (count($inData) >= 2) {
                        unset($driverInService[$index01]);
                        continue;
                    }
                    $driverInService[$index01]['dispatchOrder'] = $inData;
                    // 查找司机的用户信息
                    $driverUser = Db::name('admin_user')->where('id', $item01['user_id'])->find(); // 司机用户信息
                    $driverInService[$index01]['phone'] = empty($driverUser['mobile']) ? '用户为填手机号码' : $driverUser['mobile'];
                    $driverInService[$index01]['realname'] = empty($driverUser['realname']) ? '用户为填姓名' : $driverUser['realname'];
                    // 整理司机的车辆信息
                    $articName = Db::name('arctic')->where('id', $item01['arctic_id'])->value('name'); // 查找车型名字
                    if (!empty($articName)) {
                        $driverInService[$index01]['arctic'] = $articName;
                    } else {
                        $driverInService[$index01]['arctic'] = empty($item01['car_type']) ? '未填写车型' : $item01['car_type'];
                    }
                    $carModelName = Db::name('car_model')->where('id', $item01['car_model_id'])->value('car_model'); // 查找汽车型号名字
                    if (!empty($carModelName)) {
                        $driverInService[$index01]['car_model'] = $carModelName;
                    } else {
                        $driverInService[$index01]['car_model'] = empty($item01['car_model']) ? '未填写汽车型号' : $item01['car_model'];
                    }
                    $carBrandName = Db::name('car_brand')->where('id', $item01['car_brand_id'])->value('brand_name'); // 查找车辆品牌名字
                    if (!empty($carBrandName)) {
                        $driverInService[$index01]['brand_name'] = $carBrandName;
                    } else {
                        $driverInService[$index01]['brand_name'] = empty($item01['car_brand']) ? '未填写车辆品牌' : $item01['car_brand'];
                    }
                }
            }
            // 过滤不在条件的司机
            if (!empty($driverUserIds)) {
                foreach ($driverInService as $index78 => $value78) {
                    if (!in_array($value78['user_id'], explode(',', $driverUserIds))) {
                        unset($driverInService[$index78]);
                    }
                }
            }
            // 查找所有司机标签
            $map_tags['isdelete'] = 0;
            $map_tags['status'] = 1;
            $driver_tags = Db::name('driver_tag')
                ->where($map_tags)
                ->select();
            // 查询所有司机的等级
            $ranks = Db::name('driver_rank')->select();
            $this->view->assign('driver_tags', $driver_tags);
            $this->view->assign('ranks', $ranks);
            $this->view->assign('outOfServiceDrivers', $outOfServiceDrivers);
            $this->view->assign('driverInService', $driverInService);
            $this->view->assign('group_id', $groupId);
            $this->view->assign('group', $groupInfo);
            return $this->view->fetch();
        }
    }

    /**
     * 中止订单
     */
    public function suspend_order(Request $request)
    {
        $data = input();
        $group_id = $data['group_id'];
        $reverse_id = Db::name('dispatch_traveler_group')->where('id', $group_id)->value('reverse_id');
        $map['r.id'] = ['in', $reverse_id];
        if (!$reverse_id) {
            return ajax_return_adv_error('不存在中止订单');
        }
        if ($data['realname']) {
            $driver = Db::name('admin_user')->where('realname', 'like', '%' . $data['realname'] . '%')->field('id,realname')->select();
            $driverIds = '';
            foreach ($driver as $dk => $dv) {
                $driverIds .= $dv['id'] . ',';
            }
            $driverIds = rtrim($driverIds, ',');
            $map['r.driver_user_id'] = ['in', $driverIds];
        }
        //从换车表查询数据
        $reverse = Db::name('reverse')
            ->alias('r')
            ->join('tp_admin_user au', 'au.id=r.driver_user_id', 'left')
            ->where($map)
            ->field('r.*,au.realname,au.mobile')
            ->select();
        $total = count($reverse);
        $this->view->assign('group_id', $group_id);
        $this->view->assign('total', $total);
        $this->view->assign('reverse', $reverse);
        return $this->view->fetch();
    }

    /**
     * 点评
     */
    public function comment()
    {
        $data = input();
        //
        $comment = Db::name('dispatch_traveler_group')->where('id', $data['group_id'])->field('id,comment_praise,comment_negative')->find();
        $this->view->assign('vo', $comment);
        $this->view->assign('id', $data['group_id']);

        return $this->view->fetch();
    }

    /**
     * 点评完成
     */
    public function comments()
    {
        $data = input();
//        dump($data);\
        $res = Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->update(['comment_praise' => $data['comment_praise'], 'comment_negative' => $data['comment_negative']]);

        return ajax_return($res);
    }

    /**
     * 车调确认
     * @return mixed
     */
    public function car_confirm()
    {
        $data = input();
        $group = Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->find();
        if (!$group) {
            return ajax_return_error('不存在或未填写信息');
        }


        $update['car_confirm'] = '1';

        $re = Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->update($update);

        if ($re) {
            return ajax_return_adv('操作成功');
        } else {
            return ajax_return_error('操作失败');
        }
    }

    /**
     * 重置司机的申请结算条件
     */
    public function reset_settlement(Request $request)
    {
        if ($request->isPost()) {
            $postData = $request->param();
            $id = $postData['id'];
            if (!$id) {
                return ajax_return_adv_error('缺少参数');
            }
            $dispatch_group = Db::name('dispatch_traveler_group')->where('id', $id)->find();
            if (!$dispatch_group) {
                return ajax_return_adv_error('不存在该分组信息');
            }
            $up = Db::name('dispatch_traveler_group')->where('id', $id)
                ->update(['settlement_apply_time' => '', 'is_reject_settlement' => 0, 'reject_settlement_time' => '', 'reject_settlement_reason' => '']);
            $del = Db::name('settlement')->where('group_id', $id)->delete();
            if ($up || $del) {
                set_info($dispatch_group['driver_user_id'], '重新申请订单信息', "你好，你的订单:{$dispatch_group['title']}已被解锁,你可以重新申请结算", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));
                return ajax_return_adv('处理成功');
            } else {
                return ajax_return_adv_error('处理失败');
            }
        } else {
            return ajax_return_adv_error('操作失败');
        }
    }

    /**
     * 批量结算
     */
    public function batchSettlemen(Request $request)
    {
        if ($request->isPost()) {
            $now_time = time();
            $postData = $request->post();
//            dump($postData);
            if (empty($postData['id'])) {
                return ajax_return_adv_error('未选择要结算的派单');
            }
            // 查找所有派单数据
            $dispatchTravelerGroup = Db::name('dispatch_traveler_group')->where('id', 'in', $postData['id'])->select();
            foreach ($dispatchTravelerGroup as $index => $item) {
                if ($item['driver_user_id']) {
                    $update['dispatch_group_status'] = 'accounts';
                    $update['is_settlement'] = 1;
                    $update['settlement_time'] = $now_time;
                    $up = Db::name('dispatch_traveler_group')->where('id', $item['id'])->strict(false)->update($update);
                    if (!$up) {
                        return ajax_return_adv_error('结算失败');
                    }
                    $map['user_id'] = $item['driver_user_id'];
                    $map['type'] = "checkouted";
                    $map['dispatch_traveler_group_id'] = $item['id'];
                    $notify = Db::name('notify')->where($map)->find();
                    if ($notify) {
                        return ajax_return_adv_error('已经通知过了');
                    }
                    $date_time = date("Y-m-d H:i:s", $now_time);
                    set_info($item['driver_user_id'], '已经结算', "{$date_time} 你的订单已经结算，订单编号为{$item['id']},结算金额为{$item['settlement_money']}", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $item['id']));

                    // 增加司机的订单量
                    $driver_user_id = $item['driver_user_id'];
                    $updateDriver = Db::name('driver')->where('user_id', $driver_user_id)->setInc('order_num'); // 订单量自增1
                    if (!$updateDriver) {
                        return ajax_return_adv_error("增加id为{$driver_user_id}司机的订单量失败");
                    }
                } else {
                    return ajax_return_adv_error('未选择司机');
                }
            }
            return ajax_return_adv('结算成功!');
        } else {
            return ajax_return_adv_error('非法请求');
        }
    }

    /**
     * 进行中编辑
     * @author 邓汉炜
     * @url /admin/dispatch_traveler_group/proceedEdit
     */
    public function proceedEdit(Request $request)
    {
        if ($request->isPost()) {
            $postData = $request->post();
            // 根据分组id查找之前的旅客订单，进行旅客id的比较，如果提交的数据不一样，就会产生新的住宿旅客，旧的旅客移到旧的订单旅客表

            $groupId = $postData['id'];
            if (!$groupId) {
                return ajax_return_adv_error('缺少必要的参数');
            }
            // 验证数据
            if ($postData['traveler']['name']) {
                foreach ($postData['traveler']['name'] as $index9 => $itme09) {
                    if (empty($itme09)) {
                        return ajax_return_adv_error('有旅客存在未填写姓名');
                    }
                }
            }
            if ($postData['traveler']['sex']) {
                foreach ($postData['traveler']['sex'] as $index11 => $itme11) {
                    if (empty($itme11)) {
                        return ajax_return_adv_error('有旅客存在未填写性别');
                    }
                }
            }
            if ($postData['traveler']['phone']) {
                foreach ($postData['traveler']['phone'] as $index10 => $itme10) {
                    if (empty($itme10)) {
                        return ajax_return_adv_error('有旅客存在未填写手机号码');
                    }
                }
            }
            // 从订单旅客获取旅客数据
            $oldOrderTraveler = Db::name('order_traveler')->where('group_id', $groupId)->select();
            if (empty($oldOrderTraveler)) {
                $oldOrderTraveler = [];
            }
            $oldTravelerIds = []; // 旧的旅客id
            $oid = 0;
            foreach ($oldOrderTraveler as $index => $item) {
                $oldTravelerIds[] = $item['id'];
                $oid = $item['oid'];
            }
            $newTravelerIds = [];
            if ($postData['traveler']['id']) {
                $newTravelerIds = $postData['traveler']['id'];
            }
            $isbian = 1; // 根据他来判断旅客是否是变动
            // 判断旅客是否变动，变动就产生旧的订单旅客数据
            // ①当提交的旅客数据id长度小于旧的订单旅客id的长度
            // ② 存在name、phone等字段时，说明旅客产生变动
            if (count($newTravelerIds) != count($oldTravelerIds)) {
                self::setOldTraveller($groupId, $newTravelerIds); // 保存旧旅客数据
                // 提交删除不存在的旅客id
                if (!empty($newTravelerIds) && is_array($newTravelerIds)) {
                    foreach ($oldTravelerIds as $index => $oldTravelerId) {
                        if (!in_array($oldTravelerId, $newTravelerIds)) {
                            Db::name('order_traveler')->where('id', $oldTravelerId)->delete(); // 删除
                            $map['group_id'] = $groupId;
                            $map['oid'] = $oid;
                            $map['traveler_id'] = $oldTravelerId;
                            Db::name('dispatch_traveler')->where($map)->delete(); // 删除派单旅客
                        }
                    }
                }
                $isbian = 2;
            } elseif (count($postData['traveler']['name'])) {
                self::setOldTraveller($groupId, $newTravelerIds); // 保存就旅客数据
                $isbian = 2;
            }
            // 保存新的旅客数据
            $insert = []; // 保存到订单旅客
            $dispatchId = Db::name('dispatch_traveler_group')->where('id', $groupId)->value('dispatch_id');
            if ($isbian == 2) {
                $count = count($postData['traveler']['name']);
                for ($i = 0; $i < $count; $i++) {
                    $insert[] = [
                        'name' => $postData['traveler']['name'][$i],
                        'phone' => $postData['traveler']['phone'][$i],
                        'id_card' => $postData['traveler']['id_card'][$i],
                        'address' => $postData['traveler']['address'][$i],
                        'isaccommodation' => $postData['traveler']['isaccommodation'][$i],
                        'accommodation' => $postData['traveler']['accommodation'][$i],
                        'remark' => $postData['traveler']['remark'][$i],
                        'group_id' => $groupId,
                        'oid' => $oid,
                    ];
                }
                if (!empty($insert)) {
                    $dispatch = []; // 保存到派单旅客
                    foreach ($insert as $index => $item) {
                        $up = Db::name('order_traveler')->strict(false)->insertGetId($item);
                        logs('gengxinlvke', $up);
                        $dispatch[] = [
                            'dispatch_id' => $dispatchId,
                            'oid' => $oid,
                            'traveler_id' => $up,
                            'group_id' => $groupId,
                        ];
                    }
                    // 更新派单旅客
                    if (!empty($dispatch)) {
                        Db::name('dispatch_traveler')->strict(false)->insertAll($dispatch);
                    }
                }
            }
            // 更新分组数据
            unset($postData['traveler']);
            $postData['go_date'] = empty($postData['go_date']) ? '' : strtotime($postData['go_date']);
            $postData['end_date'] = empty($postData['end_date']) ? '' : strtotime($postData['end_date']);
            $postData['num'] = Db::name('order_traveler')->where('group_id', $groupId)->count();
            Db::name('dispatch_traveler_group')->strict(false)->update($postData);
            return ajax_return_adv('更新成功');
        } else {
            $group_id = input('id');
            $group = Db::name('dispatch_traveler_group')->where(array('id' => $group_id))->find();
            $travelers = Db::name("dispatch_traveler")->alias('dt')
                ->join("tp_order_traveler ot", "ot.id=dt.traveler_id", "left")
                ->where('dt.group_id', $group_id)
                ->field('ot.*')
                ->select();
//            dump($travelers);
            $driver_users = Db::name('driver')->alias('d')
                ->join('tp_admin_user u', 'u.id=d.user_id', 'left')
                ->field("u.*")
                ->select();
            $this->view->assign("vo", $group);
            $this->view->assign("driver_users", $driver_users);
            $this->view->assign('travelers', $travelers);

            $car_types = Db::name('car_type')->select();
            $this->view->assign("car_types", $car_types);

            return $this->view->fetch('proceed_edit');
        }
    }

    /**
     * 存放旧的订单数据
     * @author 邓汉炜
     */
    protected static function setOldTraveller($id, $newTravelerId = [])
    {
        if ($id) {
            $oldOrderTravelers = Db::name('order_traveler')
                ->where('group_id', $id)
                ->select();
            if (!empty($newTravelerId)) {
                foreach ($oldOrderTravelers as $index => $oldOrderTraveler) {
                    if (in_array($oldOrderTraveler['id'], $newTravelerId)) {
                        unset($oldOrderTravelers[$index]);
                    }
                }
            }
            $time = Db::name('old_order_traveler')
                ->where('group_id', $id)
                ->order('time', 'desc')
                ->value('time');
            if (empty($time)) {
                $time = 1; // 没有该分组的数据
            } else {
                $time = $time + 1;
            }
            $insert = [];
            foreach ($oldOrderTravelers as $key => $item) {
                $item['order_traveller_id'] = $item['id'];
                unset($item['id']);
                $item['create_time'] = time();
                $item['time'] = $time;
                $insert[] = $item;
            }
            logs('jilujiulvke', $insert);
            if (!empty($insert)) {
                $add = Db::name('old_order_traveler')->strict(false)->insertAll($insert);
                logs('jilujiulvke', $add);
            }
        }
    }

    /**司机详细资料**/
    public function details(Request $request)
    {
        $data = input();

        $vo = Db::name('driver')->where('user_id', $data['driver_user_id'])->find();
        if (!$vo) {
            return ajax_return_adv_error('不存在该司机信息');
        }
        $users = Db::name('admin_user')->where('id', $vo['user_id'])->find();
        if ($users['id']) {
            $users['user_id'] = $users['id'];
            unset($users['id']);
        }
        if (!$users) {
            return ajax_return_adv_error('不存在该司机的用户信息', 1);
        }
        //查询司机等级
        $driverRank = Db::name('driver_rank')->where('id', $vo['driver_rank_id'])->find();
        if ($driverRank) {
            $vo['driver_rank_id'] = $driverRank['name'];
        } else {
            $vo['driver_rank_id'] = '新手';
        }
        $this->view->assign('users', $users);
        $this->view->assign('vo', $vo);
        return $this->view->fetch('details');
    }

    /**
     * 未分配旅客
     * @author 颜东淦
     */
    public function undistributed_traveller(Request $request)
    {

        $data = input();

//        //搜索
        //订单ID
        if ($this->request->param("order_id")) {
            $map['o.order_id'] = array('like', "%{$this->request->param("order_id")}%");
        }

        //预订人
        if ($data['booking_people_name']) {
            $map['o.booking_people_name'] = array('like', "%{$data['booking_people_name']}%");
        }

        //预订人电话
        if ($data['booking_people_phone']) {
            $map['o.booking_people_phone'] = array('like', "%{$data['booking_people_phone']}%");
        }
        //是否已经预订房间
        if ($data['isbooking']) {
            $map['pt.isbooking'] = 1;
        }

        //平台
        if ($data['platform']) {
            $map['o.platform'] = $data['platform'];
        }

        //出行日期
        if ($data['start_time'] && $data['end_time']) {
            $map['o.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        } elseif ($data['start_time']) {
            $map['o.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['start_time'] . " 23:59:59")]);
        } elseif ($data['end_time']) {
            $map['o.start_time'] = array("between", [strtotime($data['end_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        }

        //预订人备注
        if ($data['booking_people_remark']) {
            $map['o.booking_people_remark'] = array('like', "%{$data['booking_people_remark']}%");
        }

        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");

        $map['o.dispose_status'] = 'vehicle_dispatching';
        $map['ot.group_id'] = 0;
        $map['ot.is_error'] = 0;

        //查询订单信息
        $list = Db::name('order_traveler')
            ->alias("ot")
            ->join("order o", "o.id=ot.oid", 'left')
            ->join("portion_traveler pt", "o.id=pt.oid", 'left')
            ->where($map)
            ->group('ot.oid')
            ->order('o.id desc')
            ->field("ot.*,o.*,pt.isbooking")
            ->paginate($listRows, false, ['query' => $this->request->get()]);
//        dump(Db::name('order_traveler')->getLastSql());
        $new_list = $list->toArray()['data'];
        foreach ($new_list as $key => $item) {
            if (empty($item['id'])) {
                unset($new_list[$key]);
            } else {
                $new_list[$key]['order_remark'] = Db::name('order_remark')
                    ->where('order_id', $item['order_id'])
                    ->order('id desc')
                    ->select();
                continue;
            }
        }

        $oids = [];
        $order_travelers = [];
        //整合订单ids
        foreach ($new_list as $item) {

            if ($oids[$item['order_id']] != true) {

                $travelers = $item;
                $arr = Db::name('order_traveler')->where('oid', $item['id'])->field('id')->select();
                $travelers['num'] = count($arr);
                $travelers['show_single'] = true;
                $travelers['show_mian'] = false;
                $travelers['show_between'] = false;
                $travelers['show_end'] = false;
                $travelers['route_title'] = Db::name('route')
                    ->where('id', $item['route_id'])
                    ->value('title');
                //获取该订单的旅客信息
                $travelers_info = Db::name('order_traveler')->where('oid', $item['id'])->select();
                $arr = [];
                foreach ($travelers_info as $k => $v) {
                    $arr[] = $v['id'] . '-' . $v['name'];
                }
                $info = implode(',', $arr);
                $travelers['travelers_info'] = $info;
                $travelers['travelers_info_list'] = $travelers_info;
                //查询该订单的关联订单id
                $relevance_id = Db::name('order')->where('id', $item['id'])->value('relevance_id');
                //获取订单ids
                $order_ids = Db::name('order_relevance')->where('relevance', $relevance_id)->field('order_id')->select();
                $relevance_order_list = [];
                foreach ($order_ids as $k => $v) {
                    if ($v['order_id'] != $item['id']) {
                        $relevance = Db::name('order')->where('id', $v['order_id'])->find();
                        //获取关联订单的旅客信息
                        $relevance_travelers_info = Db::name('order_traveler')->where('oid', $v['order_id'])->select();
                        $relevance['num'] = count($relevance_travelers_info);
                        $arrs = [];
                        foreach ($relevance_travelers_info as $kt => $vt) {
                            $arrs[] = $vt['id'] . '-' . $vt['name'];
                        }
                        $relevance_info = implode(',', $arrs);
                        $relevance['travelers_info'] = $relevance_info;
                        $travelers['hotel_accommodations'] = Db::name('hotel_accommodation')
                            ->alias("ha")
                            ->where('ha.oid', $item['id'])
                            ->join("hotel h","ha.hotel_id=h.id","left")
                            ->join("hotel_room_type hrt","hrt.id=ha.hotel_room_type","left")
                            ->field("ha.*,h.hotel_name,hrt.room_name")
                            ->select();;
                        $relevance['travelers_info_list'] = $relevance_travelers_info;
                        $relevance['order_remark'] = Db::name('order_remark')
                            ->where('order_id', $v['order_id'])
                            ->order('id desc')
                            ->select();
                        $relevance_order_list[] = $relevance;
                    }
                }
                $travelers['relevance_order_list'] = $relevance_order_list;
                $order_travelers[] = $travelers;
                $oids[$item['order_id']] = true;

            }

        }

//        dump($order_travelers);
        // 模板赋值显示
        $platform = Db::name('platform')->select();
        $this->view->assign('Request.param.ctime', $data);
        $this->view->assign('Request.param.start_time', $data);
        $this->view->assign('platform', $platform);
        $this->view->assign('list', $order_travelers);
        if (!empty($order_travelers)) {
            $this->view->assign("count", count($order_travelers));
        }
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());

        if ($request->isAjax()) {
            $this->view->assign('refresh', 1);
            return $this->view->fetch('ajaxpage');
        } else {
            return $this->view->fetch('undistributed_traveller');
        }
    }

    /**
     * 查看旅客信息
     * @author 颜东淦
     */
    public function traveller_info()
    {
        $data = input();
        if (!isset($data['id'])) {
            throw new \think\Exception('缺少id参数');
        }

//        //判断是否为ajax请求
//        if($this->request->isAjax()){
//            //
//        }else{

        //获取该订单信息
        $vo = Db::name('order')->where('id', $data['id'])->find();
        $this->view->assign('vo', $vo);

        //获取该订单的旅客信息
        $list = Db::name('order_traveler')->where('oid', $data['id'])->select();

        //获取平台列表
        $platform = Db::name('platform')->select();
        $this->view->assign('travelers', $list);
        //获取等级列表
        $route_list = Db::name('route')->select();
        $this->view->assign('route_list', $route_list);
        $this->view->assign('platform', $platform);
        return $this->view->fetch();
//        }
    }

    /**
     * 接送机订单
     * @author 颜东淦
     */
    public function traveller_pickup(Request $request)
    {

        $data = input();

//        //搜索
        //订单ID
        if ($this->request->param("order_id")) {
            $map['o.order_id'] = array('like', "%{$this->request->param("order_id")}%");
        }

        //预订人
        if ($data['booking_people_name']) {
            $map['o.booking_people_name'] = array('like', "%{$data['booking_people_name']}%");
        }

        //预订人电话
        if ($data['booking_people_phone']) {
            $map['o.booking_people_phone'] = array('like', "%{$data['booking_people_phone']}%");
        }

        //线路名称
        if ($data['route_title']) {
            $route = Db::name('route')->whereLike('title', "%{$data['route_title']}%")->field('id')->select();
            foreach ($route as $k => $v) {
                $ids[] = $v['id'];
            }
            $map['o.route_id'] = array('in', $ids);
        }

        //平台
        if ($data['platform']) {
            $map['o.platform'] = $data['platform'];
        }

        //出行日期
        if ($data['start_time'] && $data['end_time']) {
            $map['o.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        } elseif ($data['start_time']) {
            $map['o.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['start_time'] . " 23:59:59")]);
        } elseif ($data['end_time']) {
            $map['o.start_time'] = array("between", [strtotime($data['end_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        }

        //用车形式
        if ($data['car_form']) {
            $map['o.car_form'] = array('like', "%{$data['car_form']}%");
        }

        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");

//        $map['group_id'] = 0;

        //查询订单信息
        $list = Db::name('order')
            ->alias("o")
            ->where($map)
            ->where('is_pick_up', 1)
            ->where('is_deal_pick_up', 0)
            ->where('pick_up_time is not null')
            ->order('o.id desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

//        dump($list);
        $new_list = $list->toArray()['data'];
        foreach ($new_list as $key => $item) {
            if (empty($item['id'])) {
                unset($new_list[$key]);
            } else {
                $new_list[$key]['remark'] = Db::name('order_remark')
                    ->where('order_id', $item['order_id'])
                    ->order('id desc')
                    ->select();
                continue;
            }
        }


        $oids = [];
        $order_travelers = [];
        //整合订单ids
        foreach ($new_list as $item) {

            if ($oids[$item['order_id']] != true) {

                $travelers = $item;
                $arr = Db::name('order_traveler')->where('oid', $item['id'])->field('id')->select();
                $travelers['num'] = count($arr);
                $travelers['show_single'] = true;
                $travelers['show_mian'] = false;
                $travelers['show_between'] = false;
                $travelers['show_end'] = false;
                $travelers['route_title'] = Db::name('route')
                    ->where('id', $item['route_id'])
                    ->value('title');
                //获取该订单的旅客信息
                $travelers_info = Db::name('order_traveler')->where('oid', $item['id'])->select();
                $arr = [];
                foreach ($travelers_info as $k => $v) {
                    $arr[] = $v['id'] . '-' . $v['name'];
                }
                $info = implode(',', $arr);
                $travelers['travelers_info'] = $info;
                $travelers['travelers_info_list'] = $travelers_info;
                $order_travelers[] = $travelers;
                $oids[$item['order_id']] = true;

            }

        }

        // 模板赋值显示
        $platform = Db::name('platform')->select();
        $this->view->assign('Request.param.ctime', $data);
        $this->view->assign('Request.param.start_time', $data);
        $this->view->assign('platform', $platform);
        $this->view->assign('list', $order_travelers);
        $this->view->assign("count", count($order_travelers));
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());

        if ($request->isAjax()) {
            $this->view->assign('refresh', 1);
            return $this->view->fetch('traveller_pickup_ajaxpage');
        } else {
            return $this->view->fetch('traveller_pickup');
        }
    }

    /**
     * 派单中
     * @return mixed
     */
//    public function in_sendorders(){
//
//        $map['dtg.dispatch_group_status']='sendorders';
//        $map['dtg.driver_confirm']='0';
//
//        $data=input();
//        if($data['go_date']){
//            $map['dtg.go_date'] = array("between",[strtotime($data['go_date']." 00:00:00"),strtotime($data['go_date']." 23:59:59")]);
//        }
//        if($data['sales_id']){
//            $map['dtg.sales_id']=array('in',$data['sales_id']);
//        }
//        if($data['dispatch_group_status']){
//            $map['dtg.dispatch_group_status']=$data['dispatch_group_status'];
//        }
//        if($data['car_form']){
//            $map['dtg.car_form']=array('like',"%{$data['car_form']}%");
//        }
//        if($data['remark']){
//            $map['dtg.remark']=array('like',"%{$data['remark']}%");
//        }
//        if($data['is_settlement']||$data['is_settlement']==="0"){
//            $map['dtg.is_settlement']=$data['is_settlement'];
//        }
//        if($data['driver_user']){
//            $map['u.realname']=array('like',"%{$data['driver_user']}%");
//        }
//        $map['isreject']=false;
//        $listRows = $this->request->param('numPerPage') ? : Config::get("paginate.list_rows");
//        $list = DB('dispatch_traveler_group')
//            ->alias('dtg')
//            ->join('tp_admin_user u','u.id=dtg.driver_user_id','left')
//            ->field('dtg.*,u.realname')
//            ->where($map)
//            ->order("dtg.id desc")
//            ->paginate($listRows, false, ['query' => $this->request->get()]);
//
//        $this->view->assign('list',$list);
//        $this->view->assign("count", $list->total());
//        $this->view->assign("page", $list->render());
//        $this->view->assign('numPerPage', $list->listRows());
//        return $this->view->fetch();
//    }

    /**
     * 已接单
     * @author 颜东淦
     */
    public function in_receiving()
    {

        $map['dtg.dispatch_group_status'] = 'receiving';
        $map['dtg.driver_confirm'] = '1';

        $data = input();

        //派车单号
        if ($data['id']) {
            $map['dtg.id'] = array('like', "%{$data['id']}%");
        }
        //司机
        if ($data['realname']) {
            $mapa['realname'] = array('like', "%{$data['realname']}%");
            $au = Db::name('admin_user')->where($mapa)->field('id')->select();
            if ($au) {
                foreach ($au as $k => $v) {
                    $au_id[] = $v['id'];
                }
                $map['dtg.driver_user_id'] = array('in', $au_id);
            }
        }
        //客人
        if ($data['grname']) {
            $mapu['name'] = array('like', "%{$data['grname']}%");
            $group_id = Db::name('order_traveler')->where($mapu)->field('group_id')->select();
            if ($group_id) {
                foreach ($group_id as $k => $v) {
                    $dis_id[] = $v['group_id'];
                }
                $map['dtg.id'] = array('in', $dis_id);
            }
        }
        //出行日期
        if ($data['start_time'] && $data['end_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        } elseif ($data['start_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['start_time'] . " 23:59:59")]);
        } elseif ($data['end_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['end_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        }
        //用车形式
        if ($data['car_form']) {
            $map['dtg.car_form'] = array('=', $data['car_form']);
        }
        $map['isreject'] = false;
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
//        $list = DB('dispatch_traveler_group')
//            ->alias('dtg')
//            ->join('tp_dispatch_order dor','dor.dispatch_id=dtg.dispatch_id','left')
//            ->join('tp_order or','or.id=dor.oid','left')
//            ->join('tp_driver dr','dr.user_id=dtg.driver_user_id','left')
//            ->field('dtg.num,dtg.is_pickup,dtg.oid as dtg_oid,dtg.route_id,dtg.id,dtg.remark,dtg.dispatch_id,dtg.driver_user_id,dor.oid,dtg.go_date as start_time,dtg.end_date as end_time,dtg.car_form,dr.vehicle_level,dr.driver_rank_id')
//            ->where($map)
//            ->order("dtg.id desc")
//            ->group('dor.dispatch_id')
//            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $list = DB('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_dispatch d', 'd.id=dtg.dispatch_id', 'left')
            ->join('tp_driver dr', 'dr.user_id=dtg.driver_user_id', 'left')
            ->field('dtg.num,dtg.is_pickup,dtg.oid as dtg_oid,dtg.route_id,dtg.id,dtg.remark,dtg.dispatch_id,dtg.driver_user_id,dtg.go_date as start_time,dtg.end_date as end_time,dtg.car_form,dr.vehicle_level,dr.driver_rank_id')
            ->where($map)
            ->order("dtg.id desc")
            ->group("d.id")
            ->paginate($listRows, false, ['query' => $this->request->get()]);
//return json(['list' => $list]);
        $this->view->assign('list', $list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 接单
     * @return mixed
     */
    public function accept($data=null)
    {
        //获取数据
        if(!$data){
            $data = input();
        }

        $group = Db::name('dispatch_traveler_group')
            ->where('id', $data['group_id'])
            ->find();
//        return json(['datas' => $group]);
         //select * from dispatch_traveler_group where id = group_id
        if ($group['dispatch_group_status'] == 'receiving') {
            return ajax_return_error('订单已处理');
        }

        $update['dispatch_group_status'] = 'receiving';
        $update['driver_confirm'] = true;
        $update['receiving_time'] = NOW_TIME;

        $re = Db::name('dispatch_traveler_group')
            ->where('id', $data['group_id'])
            ->update($update);

        //如果不是接机订单
        if ($group['is_pickup'] != '1') {
            if ($re) {
                // 司机接受派单，同步住宿派单
                $group_id = $data['group_id']; // 派单id
                // 从订单旅客表获取派单旅客数据,并且有住宿要求的旅客
                $groupTravel = Db::name('order_traveler')->where('group_id', $group_id)->where('isaccommodation', '包含住宿')->select();
                //  查询派单数据
                $groupInfo = Db::name('dispatch_traveler_group')->where('id', $group_id)->find();
                // 查找司机信息
                $driver = Db::name('driver')->where('user_id', $groupInfo['driver_user_id'])->find();
                if ($groupTravel && empty($group['reverse_id'])) {
                    // 同步住宿派单
                    $insert = [
                        'driver_id' => $driver['id'],
                        'driver_user_id' => $groupInfo['driver_user_id'],
                        'number_of_guests' => count($groupTravel),
                        'departure_date' => $groupInfo['go_date'],
                        'finish_date' => $groupInfo['end_date'],
                        'group_id' => $group_id,
                        'car_form' => $groupInfo['car_form'],
                        'create_time' => time(),
                    ];
                    // 添加到表里
                    $addId = Db::name('portion_traveler')->strict(false)->insertGetId($insert);

                    //获取订单ids
                    $order_ids = Db::name('order_traveler')->group('oid')->where('group_id', $group_id)->field('id,oid,group_id')->select();

                    //更改订单状态
                    if (count($order_ids) > 1) {
                        // order_status issue已出单
                        // dispose_status normal_travel:正常出行
                        $update['order_status'] = 'issue';
                        $update['dispose_status'] = 'normal_travel';
                        foreach ($order_ids as $ok => $ov) {
                            Db::name('order')->strict(false)->where('id', $ov['oid'])->update($update);
                        }
                    }

                    logs('paidan', $addId);
                }
                return ajax_return_adv('接单成功');
            } else {
                return ajax_return_error('不存在或未填写信息');
            }
        } else {  //如果是接机订单
            //接机单不需要同步住宿
            return ajax_return_adv('接单成功');
        }
    }

    /**
     * 确认出发
     * @author 颜东淦
     */
    public function confirm_departure()
    {
        //获取数据
        $data = input();

        $group = Db::name('dispatch_traveler_group')
            ->where('id', $data['group_id'])
            ->find();

        if ($group['dispatch_group_status'] == 'proceed') {
            return ajax_return_error('已确认过出发');
        }
        $update['dispatch_group_status'] = 'proceed';
        $update['driver_confirm'] = true;
        $update['proceed_time'] = NOW_TIME;

        $re = Db::name('dispatch_traveler_group')
            ->where('id', $data['group_id'])
            ->update($update);

        if ($re) {
            return ajax_return_adv('确认成功');
        } else {
            return ajax_return_error('不存在或未填写信息');
        }
    }

    /**
     * 派车单信息
     * @author 颜东淦
     */
    public function dispatch_details()
    {
        //获取数据
        $data = input();
        //查询派车单信息
        $group = Db::name('dispatch_traveler_group')
            ->where('id', $data['group_id'])
            ->find();

        $driver = Db::name('driver')->where('user_id', $group['driver_user_id'])->field('id,user_id,vehicle_level,car_model,seats,car_brand')->find();
        $driver_info = Db::name('admin_user')->where('id', $driver['user_id'])->field('id,realname,mobile')->find();
        //司机信息
        if (empty($driver_info['realname'])) {
            $group['driver_user_name'] = '司机:' . $driver['user_id'] . '-未填写真实姓名';
        } else {
            $group['driver_user_name'] = $driver_info['realname'];
        }
        if (empty($driver_info['mobile'])) {
            $group['driver_user_mobile'] = '司机:' . $driver['user_id'] . '-未填写手机号码';
        } else {
            $group['driver_user_mobile'] = $driver_info['mobile'];
        }
        $driver['vehicle_level'] = $this->ck_fill($driver['vehicle_level'], '车辆等级');
        $driver['car_brand'] = $this->ck_fill($driver['car_brand'], '车辆品牌');
        $driver['car_model'] = $this->ck_fill($driver['car_model'], '汽车型号');
        $driver['seats'] = $this->ck_fill($driver['seats'], '座位数');
        //车辆信息
        $group['car_info'] = '车辆等级：' . $driver['vehicle_level'] . '，车辆品牌：' . $driver['car_brand'] . '，汽车型号：' . $driver['car_model'] . '，座位数：' . $driver['seats'];

        $route_info = Db::name('route')->where('id', $group['route_id'])->field('id,title,pass')->find();
        //路线信息
        $group['route_title'] = $this->ck_fill($route_info['title'], '路线名称');
        $group['route_pass'] = $this->ck_fill($route_info['route_pass'], '路线');
        $group['remark'] = $this->ck_fill($group['remark'], '备注');
        $group['dtg_remark'] = Db::name('dispatch_remark')->where('dtg_id', $group['id'])->field('dtg_id,content')->select();
        $pick_up_info = [];
        if ($group['is_pickup'] == '1') {//接机单
            $order_traveler_count = Db::name('order_traveler')->group('oid')->where('oid', $data['oid'])->field('oid')->select();
            $list = [];
            $list[0]['oid'] = $group['oid'];
            $list[0]['go_date'] = $group['go_date'];
            $list[0]['driver_user_id'] = $group['driver_user_id'];
            $list[0]['remark'] = $group['remark'];
            $list[0]['is_pickup'] = $group['is_pickup'];
            $order_travelers[0]['oid'] = $group['oid'];
            $order_travelers[0] = Db::name('order_traveler')->where('oid', $group['oid'])->select();
            $order_travelers[0]['order_remark'] = Db::name('order_remark')
                ->where('order_id', $group['oid'])
                ->order('id desc')
                ->select();
            $pick_up_info = Db::name('order')->where('id', $group['oid'])->field('pick_up_location,pick_up_time')->find();
        } else {
            $list = [];
            $order_travelers = [];
            $order_traveler_count = Db::name('order_traveler')->group('oid')->where('group_id', $data['group_id'])->field('oid')->select();
            foreach ($order_traveler_count as $k => $v) {
                $list[$k]['oid'] = $v['oid'];
                $list[$k]['go_date'] = $group['go_date'];
                $list[$k]['driver_user_id'] = $group['driver_user_id'];
                $list[$k]['remark'] = $group['remark'];
                $list[0]['is_pickup'] = $group['is_pickup'];
                $order_travelers[$k]['oid'] = $v['oid'];
                $order_travelers[$k]['order_remark'] = Db::name('order_remark')
                    ->where('order_id', $v['oid'])
                    ->order('id desc')
                    ->select();
                $order_travelers[$k] = Db::name('order_traveler')->where('oid', $v['oid'])->select();
            }
        }

        if ($pick_up_info && !empty($pick_up_info)) {
            $this->view->assign('location', $pick_up_info['pick_up_location']);
            $this->view->assign('pick_up_time', $pick_up_info['pick_up_time']);
        }
        $unf = input('unf');
        if (isset($unf)) {
            $this->view->assign('unf', $unf);
        }
        $this->view->assign('list', $list);
        $this->view->assign('group', $group);
        $this->view->assign('count', count($order_traveler_count));
        $this->view->assign('order_traveler', $order_travelers);
        return $this->view->fetch();
    }

    /**
     * 全部打散
     * @author 颜东淦
     */
    public function all_scatter()
    {
        //获取派车单id
        $id = input('id');

        //获取派车单信息
        $dispatch_info = Db::name('dispatch_traveler_group')->where('id', $id)->find();
        $dispatch_id = $dispatch_info['dispatch_id'];

        //开启事务
        Db::startTrans();

        try {
            if ($dispatch_info['is_pickup'] == 1) { //接机单处理

                //派车单状态
                switch ($dispatch_info['dispatch_group_status']) {
                    case 'undistributed'://未分配
                        //还未分配司机
                        set_info($dispatch_info['driver_user_id'], '订单分配', "您的订单编号为:{$id}的订单已被取消", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));

                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $dispatch_info['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "您的订单编号为:{$id}的订单已被取消");
                            logs('paidan', $ret);
                        }
                        break;
                    case 'sendorders'://派单中
                        //查询该司机在是否还存在派车单
                        $dispatchOrder = Db::name('dispatch_traveler_group')
                            ->where('dispatch_group_status', 'in', 'sendorders,proceed')
                            ->where('driver_user_id', $dispatch_info['driver_user_id'])
                            ->select();
                        if (count($dispatchOrder) == 0) {
                            //如果没有释放该司机
                            Db::name("driver")->strict(false)->where('user_id', $dispatch_info['driver_user_id'])->update(array('inservice' => 0));
                        }
                        set_info($dispatch_info['driver_user_id'], '订单分配', "您的订单编号为:{$id}的订单已被取消", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));

                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $dispatch_info['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "您的订单编号为:{$id}的订单已被取消");
                            logs('paidan', $ret);
                        }
                        break;
                    case 'receiving'://已接单
                        //查询该司机在是否还存在派车单
                        $dispatchOrder = Db::name('dispatch_traveler_group')
                            ->where('dispatch_group_status', 'in', 'sendorders,proceed')
                            ->where('driver_user_id', $dispatch_info['driver_user_id'])
                            ->select();
                        if (count($dispatchOrder) == 0) {
                            //如果没有释放该司机
                            Db::name("driver")->strict(false)->where('user_id', $dispatch_info['driver_user_id'])->update(array('inservice' => 0));
                        }
                        set_info($dispatch_info['driver_user_id'], '订单分配', "您的订单编号为:{$id}的订单已被取消", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));

                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $dispatch_info['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "您的订单编号为:{$id}的订单已被取消");
                            logs('paidan', $ret);
                        }
                        break;
                    default:
                        $msg['status'] = false;
                        $msg['msg'] = '该派车单在当前状态下，不可修改！';
                        return json($msg);
                }

                //删除派车单相关表数据
                Db::name("dispatch")->where('id', $dispatch_id)->delete();
                Db::name("dispatch_traveler_group")->where('id', $id)->delete();

                //更新订单接机分配状态
                Db::name("order")->strict(false)->where('id', $dispatch_info['oid'])->update(array('is_pick_up' => 0));

            } else {

                //获取订单ids
                $order_ids = Db::name('order_traveler')->group('oid')->where('group_id', $id)->field('id,oid,group_id')->select();

                //将所有订单改为异常状态
                if (count($order_ids) > 1) {
                    // order_status pending 待出单
                    // dispose_status error:异常
                    $update['order_status'] = 'pending';
                    $update['dispose_status'] = 'error';
                    foreach ($order_ids as $ok => $ov) {
                        Db::name('order')->strict(false)->where('id', $ov['oid'])->update($update);
                    }
                }

                //正常派车单处理
                switch ($dispatch_info['dispatch_group_status']) {//派车单状态
                    case 'undistributed'://未分配
                        //还未分配司机
                        set_info($dispatch_info['driver_user_id'], '订单分配', "您的订单编号为:{$id}的订单已被取消", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));

                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $dispatch_info['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "您的订单编号为:{$id}的订单已被取消");
                            logs('paidan', $ret);
                        }
                        break;
                    case 'sendorders'://派单中
                        //查询该司机在是否还存在派车单
                        $dispatchOrder = Db::name('dispatch_traveler_group')
                            ->where('dispatch_group_status', 'in', 'sendorders,proceed')
                            ->where('driver_user_id', $dispatch_info['driver_user_id'])
                            ->select();
                        if (count($dispatchOrder) == 0) {
                            //如果没有释放该司机
                            Db::name("driver")->strict(false)->where('user_id', $dispatch_info['driver_user_id'])->update(array('inservice' => 0));
                        }
                        set_info($dispatch_info['driver_user_id'], '订单分配', "您的订单编号为:{$id}的订单已被取消", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));

                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $dispatch_info['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "您的订单编号为:{$id}的订单已被取消");
                            logs('paidan', $ret);
                        }
                        break;
                    case 'receiving'://已接单
                        //查询该司机在是否还存在派车单
                        $dispatchOrder = Db::name('dispatch_traveler_group')
                            ->where('dispatch_group_status', 'in', 'sendorders,proceed')
                            ->where('driver_user_id', $dispatch_info['driver_user_id'])
                            ->select();
                        if (count($dispatchOrder) == 0) {
                            //如果没有释放该司机
                            Db::name("driver")->strict(false)->where('user_id', $dispatch_info['driver_user_id'])->update(array('inservice' => 0));
                        }
                        set_info($dispatch_info['driver_user_id'], '订单分配', "您的订单编号为:{$id}的订单已被取消", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));

                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $dispatch_info['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "您的订单编号为:{$id}的订单已被取消");
                            logs('paidan', $ret);
                        }

                        //进行房调操作删除住宿派单
                        Db::name('portion_traveler')->where('group_id', $dispatch_info['id'])->delete();
                        break;
                    default:
                        $msg['status'] = false;
                        $msg['msg'] = '该派车单在当前状态下，不可修改！';
                        return json($msg);
                }

                //获取订单ID
                $oids = Db::name("order_traveler")->group('oid')->where('group_id', $id)->field('id,oid')->select();

                //订单旅客回滚为未分配状态并将订单旅客改为异常状态，等待售后处理完成才再可分配
                Db::name("order_traveler")->where('group_id', $id)->update(array('group_id' => 0, 'is_error' => '1'));

                //将订单状态改为未分配
                if (count($oids) > 0) {
                    foreach ($oids as $k => $v) {
                        //修改订单状态
//                        Db::name("order")->strict(false)->where('id',$v['oid'])->update(array('isallot'=>0,'allot_end'=>0));
                        Db::name("order")->strict(false)->where('id', $v['oid'])->update(array('isallot' => 0));
                    }
                }

                //删除保险记录
                Db::name('dispatch_insurance')->where('group_id', $id)->delete();

                //删除派车单相关表数据
                Db::name('dispatch')->where('id', $dispatch_id)->delete();
                Db::name('dispatch_order')->where('dispatch_id', $dispatch_id)->delete();
                Db::name('dispatch_traveler')->where('dispatch_id', $dispatch_id)->delete();
                Db::name('dispatch_traveler_group')->where('id', $id)->delete();
            }

            //操作完成提交事务
            Db::commit();
            //返回状态及信息
            $msg['status'] = true;
            $msg['data'] = $dispatch_info;
            $msg['msg'] = '操作成功！';
            return json($msg);
        } catch (\Exception $e) {
            //回滚事务
            Db::rollback();
            //返回状态及信息
            $msg['msg'] = $e->getMessage();
            $msg['status'] = false;
            return json($msg);
        }
    }

    /**
     * 单个打散
     * @author 颜东淦
     */
    public function scatter()
    {
        //获取派车单id与订单id
        $id = input('id');
        $order_id = input('order_id');

        //获取派车单信息
        $dispatch_info = Db::name('dispatch_traveler_group')->where('id', $id)->find();
        $dispatch_id = $dispatch_info['dispatch_id'];

        //开启事务
        Db::startTrans();

        try {
            if ($dispatch_info['is_pickup'] == 1) { //接机单处理

                //派车单状态
                switch ($dispatch_info['dispatch_group_status']) {
                    case 'undistributed'://未分配
                        //还未分配司机
                        set_info($dispatch_info['driver_user_id'], '订单分配', "您的订单编号为:{$id}的订单有新的变动，请注意查收", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));

                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $dispatch_info['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "您的订单编号为:{$id}的订单有新的变动，请注意查收");
                            logs('paidan', $ret);
                        }
                        break;
                    case 'sendorders'://派单中
                        //释放司机
                        Db::name("driver")->strict(false)->where('user_id', $dispatch_info['driver_user_id'])->update(array('inservice' => 0));
                        set_info($dispatch_info['driver_user_id'], '订单分配', "您的订单编号为:{$id}的订单有新的变动，请注意查收", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));

                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $dispatch_info['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "您的订单编号为:{$id}的订单有新的变动，请注意查收");
                            logs('paidan', $ret);
                        }
                        break;
                    case 'receiving'://已接单
                        //释放司机
                        Db::name("driver")->strict(false)->where('user_id', $dispatch_info['driver_user_id'])->update(array('inservice' => 0));
                        set_info($dispatch_info['driver_user_id'], '订单分配', "您的订单编号为:{$id}的订单有新的变动，请注意查收", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));

                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $dispatch_info['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "您的订单编号为:{$id}的订单有新的变动，请注意查收");
                            logs('paidan', $ret);
                        }
                        break;
                    default:
                        $msg['status'] = false;
                        $msg['msg'] = '该派车单在当前状态下，不可修改！';
                        return json($msg);
                }

                //删除派车单相关表数据
                Db::name("dispatch")->where('id', $dispatch_id)->delete();
                Db::name("dispatch_traveler_group")->where('id', $id)->delete();

                //更新订单接机分配状态
                Db::name("order")->strict(false)->where('id', $dispatch_info['oid'])->update(array('is_pick_up' => 0));

            } else {
                //判断该派车单是否存在多个订单
                $order_num = Db::name('order_traveler')->where('group_id', $id)->group('oid')->field('id')->select();

                //如果只存在一个订单则不可打散
                if (count($order_num) > 0 && count($order_num) == 1) {
                    $msg['status'] = false;
                    $msg['msg'] = '该派车单只存在一个订单，不可进行打散操作！';
                    return json($msg);
                }

                //将订单改为异常状态
                // order_status pending 待出单
                // dispose_status error:异常
//                $update['order_status'] = 'pending';
//                $update['dispose_status'] = 'error';
//                Db::name('order')->strict(false)->where('id',$order_id)->update($update);

                //修改订单状态为可派车状态
                Db::name('order')->strict(false)->where('id', $order_id)->update(array('dispose_status' => 'vehicle_dispatching'));

                //正常派车单处理
                switch ($dispatch_info['dispatch_group_status']) {//派车单状态
                    case 'undistributed'://未分配
                        //还未分配司机
                        set_info($dispatch_info['driver_user_id'], '订单分配', "您的订单编号为:{$id}的订单有新的变动，请注意查收", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));

                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $dispatch_info['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "您的订单编号为:{$id}的订单有新的变动，请注意查收");
                            logs('paidan', $ret);
                        }
                        break;
                    case 'sendorders'://派单中
                        set_info($dispatch_info['driver_user_id'], '订单分配', "您的订单编号为:{$id}的订单有新的变动，请注意查收", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));

                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $dispatch_info['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "您的订单编号为:{$id}的订单有新的变动，请注意查收");
                            logs('paidan', $ret);
                        }
                        break;
                    case 'receiving'://已接单
                        set_info($dispatch_info['driver_user_id'], '订单分配', "您的订单编号为:{$id}的订单有新的变动，请注意查收", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $id));

                        // 查找该司机的手机号码
                        $mobile = Db::name('admin_user')->where('id', $dispatch_info['driver_user_id'])->value('mobile');
                        if ($mobile) {
                            $ret = send_message($mobile, "您的订单编号为:{$id}的订单有新的变动，请注意查收");
                            logs('paidan', $ret);
                        }
                        break;
                    default:
                        $msg['status'] = false;
                        $msg['msg'] = '该派车单在当前状态下，不可修改！';
                        return json($msg);
                }

                //订单旅客回滚为未分配状态并将订单旅客改为异常状态，等待售后处理完成才再可分配
//                Db::name("order_traveler")->where('group_id',$id)->where('oid',$order_id)->update(array('group_id'=>0,'is_error'=>'1'));
                //订单旅客回滚为未分配状态
                Db::name("order_traveler")->where('group_id', $id)->where('oid', $order_id)->update(array('group_id' => 0));

                //将订单状态改为未分配
                Db::name("order")->strict(false)->where('id', $order_id)->update(array('isallot' => 0));

//                //将订单状态改为未分配
//                if(count($oids)>0){
//                    foreach ($oids as $k => $v){
//                        //修改订单状态
//                        Db::name("order")->strict(false)->where('id',$v['oid'])->update(array('isallot'=>0,'allot_end'=>0));
//                    }
//                }

                //删除派车单相关表数据
                Db::name('dispatch_order')->where('dispatch_id', $dispatch_id)->where('oid', $order_id)->delete();
                Db::name('dispatch_traveler')->where('dispatch_id', $dispatch_id)->where('oid', $order_id)->delete();
                Db::name('dispatch_traveler_group')->where('id', $id)->setDec('num', 1);
            }

            //操作完成提交事务
            Db::commit();
            //返回状态及信息
            $msg['status'] = true;
            $msg['data'] = $dispatch_info;
            $msg['msg'] = '操作成功！';
            return json($msg);
        } catch (\Exception $e) {
            //回滚事务
            Db::rollback();
            //返回状态及信息
            $msg['msg'] = $e->getMessage();
            $msg['status'] = false;
            return json($msg);
        }
    }

    /**
     * 单个添加订单到派车单
     * @author 颜东淦
     */
    public function add_single_order_to_dispatch(Request $request)
    {
        if ($request->isAjax()) {
            $data = input();

            //获取派车单信息
            $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $data['id'])->find();

            //接机单不可修改
            if ($dispatch_traveler_group['is_pickup'] == 1) {
                $msg['status'] = false;
                $msg['msg'] = '该派车单为接机单且在当前状态下，不可修改！';
                return json($msg);
            }

            $arr = [];
            //判断订单旅客路线是否一致
            foreach ($data['groups']['traveler_id'] as $gk => $gv) {
                $oid = Db::name('order_traveler')->where('id', $gv)->value('oid');
                $arr[$oid] = true;
            }
            $arrs = array_keys($arr);
            $ck_t = [];
            foreach ($arrs as $kk => $vv) {
                $route_id = Db::name('order')->where('id', $vv)->value('route_id');
                $ck_t[$route_id] = true;
            }
            $route_ids = array_keys($ck_t);

            if (count($route_ids) > 1) {
                return ajax_return_error("旅客订单路线不一致");
            }

            //判断路线是否与派车单一致
            if ($route_ids[0] !== $dispatch_traveler_group['route_id']) {
                return ajax_return_error("旅客订单路线与派车单不一致");
            }

            //添加分组

            //添加派车单旅客

            //更新订单旅客分组信息
            return ajax_return_error('待开发中');
            //派车单状态
            switch ($dispatch_traveler_group['dispatch_group_status']) {
                case 'undistributed'://未分配
                    //未分配司机无需通知司机
                    break;
                case 'sendorders'://派单中
                    //分配司机需通知司机订单变动
                    set_info($dispatch_traveler_group['driver_user_id'], '订单分配', "您的订单编号为:{$data['id']}的订单有新的变动，请注意查收", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $data['id']));

                    // 查找该司机的手机号码
                    $mobile = Db::name('admin_user')->where('id', $dispatch_traveler_group['driver_user_id'])->value('mobile');
                    if ($mobile) {
                        $ret = send_message($mobile, "您的订单编号为:{$data['id']}的订单有新的变动，请注意查收");
                        logs('paidan', $ret);
                    }
                    break;
                default:
                    $msg['status'] = false;
                    $msg['msg'] = '该派车单在当前状态下，不可修改！';
                    return json($msg);
            }


            return ajax_return_error('123123123');
        } else {
            $data = input();

            if ($data['id']) {
                $route_id = Db::name('dispatch_traveler_group')->where('id', $data['id'])->value('route_id');
                $map['o.route_id'] = $route_id;
            }
//        //搜索
            //订单ID
            if ($this->request->param("order_id")) {
                $map['o.order_id'] = array('like', "%{$this->request->param("order_id")}%");
            }

            //预订人
            if ($data['booking_people_name']) {
                $map['o.booking_people_name'] = array('like', "%{$data['booking_people_name']}%");
            }

            //预订人电话
            if ($data['booking_people_phone']) {
                $map['o.booking_people_phone'] = array('like', "%{$data['booking_people_phone']}%");
            }

            //平台
            if ($data['platform']) {
                $map['o.platform'] = $data['platform'];
            }

            //出行日期
            if ($data['start_time'] && $data['end_time']) {
                $map['o.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
            } elseif ($data['start_time']) {
                $map['o.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['start_time'] . " 23:59:59")]);
            } elseif ($data['end_time']) {
                $map['o.start_time'] = array("between", [strtotime($data['end_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
            }

            //预订人备注
            if ($data['booking_people_remark']) {
                $map['o.booking_people_remark'] = array('like', "%{$data['booking_people_remark']}%");
            }

            $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");

            $map['group_id'] = 0;
            $map['is_error'] = 0;

            //查询订单信息
            $list = Db::name('order_traveler')
                ->alias("ot")
                ->join("order o", "o.id=ot.oid", 'left')
                ->where($map)
                ->group('oid')
                ->order('o.id desc')
                ->paginate($listRows, false, ['query' => $this->request->get()]);

            $new_list = $list->toArray()['data'];
            foreach ($new_list as $key => $item) {
                if (empty($item['id'])) {
                    unset($new_list[$key]);
                } else {
                    $new_list[$key]['order_remark'] = Db::name('order_remark')
                        ->where('order_id', $item['order_id'])
                        ->order('id desc')
                        ->select();
                    continue;
                }
            }

            $oids = [];
            $order_travelers = [];
            //整合订单ids
            foreach ($new_list as $item) {

                if ($oids[$item['order_id']] != true) {

                    $travelers = $item;
                    $arr = Db::name('order_traveler')->where('oid', $item['id'])->field('id')->select();
                    $travelers['num'] = count($arr);
                    $travelers['show_single'] = true;
                    $travelers['show_mian'] = false;
                    $travelers['show_between'] = false;
                    $travelers['show_end'] = false;
                    $travelers['route_title'] = Db::name('route')
                        ->where('id', $item['route_id'])
                        ->value('title');
                    //获取该订单的旅客信息
                    $travelers_info = Db::name('order_traveler')->where('oid', $item['id'])->select();
                    $arr = [];
                    foreach ($travelers_info as $k => $v) {
                        $arr[] = $v['id'] . '-' . $v['name'];
                    }
                    $info = implode(',', $arr);
                    $travelers['travelers_info'] = $info;
                    $travelers['travelers_info_list'] = $travelers_info;
                    $order_travelers[] = $travelers;
                    $oids[$item['order_id']] = true;

                }

            }

            // 模板赋值显示
            $platform = Db::name('platform')->select();
            $this->view->assign('Request.param.ctime', $data);
            $this->view->assign('Request.param.start_time', $data);
            $this->view->assign('platform', $platform);
            $this->view->assign('add_group_id', $data['id']);
            $this->view->assign('list', $order_travelers);
            if (!empty($order_travelers)) {
                $this->view->assign("count", count($order_travelers));
            }
            $this->view->assign("page", $list->render());
            $this->view->assign('numPerPage', $list->listRows());
            return $this->view->fetch();
        }
    }

    /**
     * 进行中
     * @author 颜东淦
     */
    public function in_proceed()
    {
        $data = input();

        $map['dtg.dispatch_group_status'] = 'proceed';

        //派车单号
        if ($data['id']) {
            $map['dtg.id'] = array('like', "%{$data['id']}%");
        }
        //客人
        if ($data['grname']) {
            $mapu['name'] = array('like', "%{$data['grname']}%");
            $group_id = Db::name('order_traveler')->where($mapu)->field('group_id')->select();
            if ($group_id) {
                foreach ($group_id as $k => $v) {
                    $dis_id[] = $v['group_id'];
                }
                $map['dtg.id'] = array('in', $dis_id);
            }
        }
        //司机
        if ($data['realname']) {
            $mapa['realname'] = array('like', "%{$data['realname']}%");
            $au = Db::name('admin_user')->where($mapa)->field('id')->select();
            if ($au) {
                foreach ($au as $k => $v) {
                    $au_id[] = $v['id'];
                }
                $map['dtg.driver_user_id'] = array('in', $au_id);
            }
        }
        //出行日期
        if ($data['start_time'] && $data['end_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        } elseif ($data['start_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['start_time'] . " 00:00:00"), strtotime($data['start_time'] . " 23:59:59")]);
        } elseif ($data['end_time']) {
            $map['or.start_time'] = array("between", [strtotime($data['end_time'] . " 00:00:00"), strtotime($data['end_time'] . " 23:59:59")]);
        }
        //用车形式
        if ($data['car_form']) {
            $map['dtg.car_form'] = array('=', $data['car_form']);
        }

        $map['isreject'] = false;

        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
//        $list = DB('dispatch_traveler_group')
//            ->alias('dtg')
//            ->join('tp_dispatch_order dor','dor.dispatch_id=dtg.dispatch_id','left')
//            ->join('tp_order or','or.id=dor.oid','left')
//            ->join('tp_driver dr','dr.user_id=dtg.driver_user_id','left')
//            ->field('dtg.is_suspend,dtg.num,dtg.is_pickup,dtg.oid as dtg_oid,dtg.route_id,dtg.id,dtg.remark,dtg.dispatch_id,dtg.driver_user_id,dor.oid,dtg.go_date as start_time,dtg.end_date as end_time,dtg.car_form,dr.vehicle_level,dr.driver_rank_id')
//            ->where($map)
//            ->order("dtg.id desc")
//            ->group("dor.dispatch_id")
//            ->paginate($listRows, false, ['query' => $this->request->get()]);
        $list = DB('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_dispatch d', 'd.id=dtg.dispatch_id', 'left')
            ->join('tp_driver dr', 'dr.user_id=dtg.driver_user_id', 'left')
            ->field('dtg.is_suspend,dtg.num,dtg.is_pickup,dtg.oid as dtg_oid,dtg.route_id,dtg.id,dtg.remark,dtg.dispatch_id,dtg.driver_user_id,dtg.go_date as start_time,dtg.end_date as end_time,dtg.car_form,dr.vehicle_level,dr.driver_rank_id')
            ->where($map)
            ->order("dtg.id desc")
            ->group("d.id")
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        $list_data = $list->toArray();
        if ($list_data['data']) {
            foreach ($list_data['data'] as $ldk => $ldv) {
                if ($ldv['is_pickup'] == '1') { //接机单
                    //查找客人姓名
                    $travelers = Db::name("order_traveler")
                        ->where('oid', $ldv['oid'])
                        ->select();
                } else {
                    //查找客人姓名
                    $travelers = Db::name("dispatch_traveler")->alias('dt')
                        ->join("tp_order_traveler ot", "ot.id=dt.traveler_id", "left")
                        ->where('dt.group_id', $ldv['id'])
                        ->field('ot.*')
                        ->select();
                }
                $booking_people_name = '';
                foreach ($travelers as $tk => $tv) {
                    $booking_people_name .= $tv['name'] . '+';
                }
                $booking_people_name = rtrim($booking_people_name, '+');
                $list_data['data'][$ldk]['booking_people_name'] = $booking_people_name;
            }
        }
        $show = 1;
        $this->view->assign('list', $list);
        $this->view->assign('list_data', $list_data['data']);
        $this->view->assign('show', $show);
//        $this->view->assign('searchCondition',$searchData);//搜索条件
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 申请结算
     * @author 颜东淦
     */
    public function apply_settlement(Request $request)
    {

        if ($request->isAjax()) {
            $data = input();

            if ($data['driver_from'] == 1) {
                //公司车辆申请结算
                $rule = [
                    'id' => 'require',
                    'prepaid_expenses' => 'require|number',
                    'start_gauge_value' => 'require|number',
                    'end_gauge_value' => 'require|number',
                    'start_odometer_value' => 'require|number',
                    'end_odometer_value' => 'require|number',
                    'insurance_expenses' => 'require|number',
                    'comment_praise' => 'require|number',
                    'comment_negative' => 'require|number',
                    'feedback' => 'number|min:0.01',
                    'is_reach_standard' => 'require|in:0,1',
                    'deduct_money' => 'number',
                    'other_deduct_money' => 'number',
                ];
                $msg = [
                    'id.require' => '参数错误',
                    'prepaid_expenses.require' => '请填写预支付标准',
                    'prepaid_expenses.number' => '预支付标准格式填写错误，请输入数字',
                    'start_gauge_value.require' => '请填写起始油表',
                    'end_gauge_value.require' => '请填写结束油表',
                    'start_gauge_value.number' => '起始油表格式填写错误，请输入数字',
                    'end_gauge_value.number' => '结束油表格式填写错误，请输入数字',
                    'start_odometer_value.require' => '请填写起始里程',
                    'end_odometer_value.require' => '请填写结束里程',
                    'start_odometer_value.number' => '起始里程格式填写错误，请输入数字',
                    'end_odometer_value.number' => '结束里程格式填写错误，请输入数字',
                    'insurance_expenses.require' => '请填写保险费用',
                    'insurance_expenses.number' => '保险费用格式填写错误，请输入数字',
                    'comment_praise.require' => '请填写好评数',
                    'comment_praise.number' => '好评数格式填写错误，请输入数字',
                    'comment_negative.require' => '请填写差评数',
                    'comment_negative.number' => '差评数格式填写错误，请输入数字',
                    'feedback.number' => '好评率格式填写错误，请输入数字',
                    'is_reach_standard.require' => '请选择是否达标',
                    'is_reach_standard.in' => '是否达标只能从是或否中选择',
                    'deduct_money.number' => '差评扣款格式填写错误，请输入数字',
                    'other_deduct_money.number' => '其它扣款格式填写错误，请输入数字',
                ];

                $validate = new Validate($rule, $msg);
                $result = $validate->check($data);
                if (!$result) {
                    return ajax_return_error($validate->getError());
                }
            } else {
                //外签车辆申请结算
                $rule = [
                    'id' => 'require',
                    'driver_fee' => 'require|number',
                    'driver_compensation' => 'require|number',
                    'company_compensation' => 'require|number',
                    'insurance_expenses' => 'require|number',
                    'deduct_money' => 'number',
                    'other_deduct_money' => 'number',
                    'comment_praise' => 'require|number',
                    'comment_negative' => 'require|number',
                    'feedback' => 'number|min:0.01',
                    'is_reach_standard' => 'require|in:0,1',
                ];
                $msg = [
                    'id.require' => '参数错误',
                    'driver_fee.require' => '请填写司机费用',
                    'driver_fee.number' => '司机费用格式填写错误，请输入数字',
                    'driver_compensation.require' => '请填写司机补偿金',
                    'driver_compensation.number' => '司机补偿金格式填写错误，请输入数字',
                    'company_compensation.require' => '请填写公司补偿金',
                    'company_compensation.number' => '公司补偿金格式填写错误，请输入数字',
                    'insurance_expenses.require' => '请填写保险费用',
                    'insurance_expenses.number' => '保险费用格式填写错误，请输入数字',
                    'comment_praise.require' => '请填写好评数',
                    'comment_praise.number' => '好评数格式填写错误，请输入数字',
                    'comment_negative.require' => '请填写差评数',
                    'comment_negative.number' => '差评数格式填写错误，请输入数字',
                    'feedback.number' => '好评率格式填写错误，请输入数字',
                    'is_reach_standard.require' => '请选择是否达标',
                    'is_reach_standard.in' => '是否达标只能从是或否中选择',
                    'deduct_money.number' => '差评扣款格式填写错误，请输入数字',
                    'other_deduct_money.number' => '其它扣款格式填写错误，请输入数字',
                ];

                $validate = new Validate($rule, $msg);
                $result = $validate->check($data);
                if (!$result) {
                    return ajax_return_error($validate->getError());
                }
            }

            $group_id = $data['id'];

            $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $group_id)->find();

            if ($dispatch_traveler_group['driver_user_id']) {

                //查询是否存在保险费用记录
                $dispatch_insurance = Db::name('dispatch_insurance')->where('group_id',$group_id)->find();
                if(!$dispatch_insurance){
                    Db::name('dispatch_insurance')->strict(false)->insert(array('group_id'=>$group_id,'insurance_money'=>$data['insurance_expenses']));
                }else{
                    //更新派车单保险费用
                    Db::name('dispatch_insurance')->strict(false)->where('group_id',$group_id)->update(array('insurance_money'=>$data['insurance_expenses']));
                }

                if ($data['type'] && $data['type'] == 'reapply') {//如果为再次申请
                    if ($dispatch_traveler_group['dispatch_group_status'] != 'accounts' || $dispatch_traveler_group['is_reject_settlement'] != '1') {
                        return ajax_return_error('此派车单当前状态不可再次申请结算');
                    }
                    if ($dispatch_traveler_group['is_apply_settlement'] == '1') {
                        return ajax_return_error('此派车单已申请结算');
                    }
                    if ($dispatch_traveler_group['is_settlement'] == '1') {
                        return ajax_return_error('此派车单已结算');
                    }

                    unset($data['id']);

                    $data['is_apply_settlement'] = 1;

                    $data['dispatch_group_status'] = 'accounts';

                    $data['is_reject_settlement'] = 0;

                    $data['apply_settlement_time'] = time();

                    if (empty($data['feedback']) || $data['feedback'] != $dispatch_traveler_group['feedback'] || $data['comment_praise'] != $dispatch_traveler_group['comment_praise'] || $data['comment_negative'] != $dispatch_traveler_group['comment_negative']) {
                        if(($data['comment_negative'] + $data['comment_praise'])>0){
                            $data['feedback'] = $data['comment_praise'] / ($data['comment_negative'] + $data['comment_praise']);
                            $data['feedback'] = round($data['feedback'], 4) * 100;
                        }
                    }

                    $res = Db::name('dispatch_traveler_group')->strict(false)->where('id', $group_id)->update($data);

                    if ($res) {
                        return ajax_return_adv('申请结算成功');
                    } else {
                        return ajax_return_error('申请结算失败');
                    }

                } else {
                    if ($dispatch_traveler_group['dispatch_group_status'] != 'achieve') {
                        return ajax_return_error('此派车单当前状态不可申请结算');
                    }

                    if ($dispatch_traveler_group['is_apply_settlement'] == '1') {
                        return ajax_return_error('此派车单已申请结算');
                    }

                    unset($data['id']);

                    if ($data['driver_from'] == 1) {
                        Db::name('driver_prepayment')->strict(false)->insert(['group_id' => $group_id, 'remark' => $data['remark']]);

                        //如果未公司车辆则直接进入已结算
                        $data['is_settlement'] = 1;

                        $data['dispatch_group_status'] = 'accounts';
                    } else {
                        $data['is_apply_settlement'] = 1;

                        $data['dispatch_group_status'] = 'accounts';
                    }

                    $data['apply_settlement_time'] = time();

                    if (empty($data['feedback']) || $data['feedback'] != $dispatch_traveler_group['feedback'] || $data['comment_praise'] != $dispatch_traveler_group['comment_praise'] || $data['comment_negative'] != $dispatch_traveler_group['comment_negative']) {
                        if(($data['comment_negative'] + $data['comment_praise'])>0){
                            $data['feedback'] = $data['comment_praise'] / ($data['comment_negative'] + $data['comment_praise']);
                            $data['feedback'] = round($data['feedback'], 4) * 100;

                        }
                    }

                    $res = Db::name('dispatch_traveler_group')->strict(false)->where('id', $group_id)->update($data);

                    if ($res) {
                        return ajax_return_adv('申请结算成功');
                    } else {
                        return ajax_return_adv_error('申请结算失败');
                    }
                }
            } else {
                return ajax_return_error('未分配司导');
            }
        } else {
            $group_id = input('group_id');
            $data = input();
            if (isset($data['type']) && $data['type'] == 'reapply') {
                $this->view->assign('type', 'reapply');
            }
            $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $group_id)->find();

            //获取司机来源
            if (!$dispatch_traveler_group['driver_user_id']) {
                return ajax_return_error('未分配司导');
            }
            $driver_type = Db::name('driver')->where('user_id', $dispatch_traveler_group['driver_user_id'])->value('driver_type');
            $driver_from = Db::name('driver_type')->where('id', $driver_type)->value('from');

            //查询是否存在保险费用记录
            $dispatch_insurance = Db::name('dispatch_insurance')->where('group_id',$group_id)->find();
            if(!$dispatch_insurance){
                Db::name('dispatch_insurance')->strict(false)->insert(array('group_id'=>$group_id));
            }

            //获取订单ids
            $oids = Db::name('order_traveler')->group('oid')->where('group_id', $group_id)->field('id,oid,group_id')->select();
            //获取订单信息以及编号
            $order_info = [];
            $order_ids = [];
            $comment_praise = 0;
            $comment_negative = 0;
            $not_comment = 0;
            foreach ($oids as $k => $v) {
                $temp = Db::name('order')->where('id', $v['oid'])->find();
                $order_ids[] = $temp['order_id'];
                switch ($temp['dispose_status']) {
                    case 'no_contact':
                        $temp['dispose_status_name'] = '未联系';
                        break;
                    case 'no_collection':
                        $temp['dispose_status_name'] = '未收集';
                        break;
                    case 'vehicle_dispatching':
                        $temp['dispose_status_name'] = '可派车';
                        break;
                    case 'normal_travel':
                        $temp['dispose_status_name'] = '正常出行';
                        break;
                    case 'success_travel':
                        $temp['dispose_status_name'] = '完成出行';
                        break;
                    case 'error':
                        $temp['dispose_status_name'] = '异常';
                        break;
                    default:
                        $temp['dispose_status_name'] = '暂无';
                }
                //获取订单评价
                $order_evaluate = Db::name('order_evaluate')->where('oid', $temp['order_id'])->find();
                if (!empty($order_evaluate)) {
                    $order_evaluate['img_src'] = explode(',', $order_evaluate['img_src']);
                    if ($order_evaluate['comment_status'] == '1') {
                        $temp['order_evaluate_status'] = '好评';
                        $comment_praise = $comment_praise + 1;
                    } else if ($order_evaluate['comment_status'] == '2') {
                        $temp['order_evaluate_status'] = '差评';
                        $comment_negative = $comment_negative + 1;
                    } else {
                        $temp['order_evaluate_status'] = '未评价';
                        $not_comment = $not_comment + 1;
                    }
                    $order_evaluate['platform_name'] = Db::name('platform')->where('platform_name', $order_evaluate['platform'])->value('name');
                    if (empty($order_evaluate['platform_name'])) {
                        $order_evaluate['platform_name'] = '暂无信息';
                    }
                } else {
                    $temp['platform_name'] = Db::name('platform')->where('platform_name', $temp['platform'])->value('name');
                    $temp['order_evaluate_status'] = '未评价';
                    $not_comment = $not_comment + 1;
                }
                $temp['order_evaluate'] = $order_evaluate;
                $order_info[] = $temp;
            }
            $this->view->assign('driver_from', $driver_from);
            $this->view->assign('order_info', $order_info);
            $this->view->assign('not_comment', $not_comment);
            $this->view->assign('comment_negative', $comment_negative);
            $this->view->assign('comment_praise', $comment_praise);
            $this->view->assign('data', $dispatch_traveler_group);
            return $this->view->fetch();
        }
    }

    /**
     * 取消结算
     * @author 颜东淦
     */
    public function cancel_settlement()
    {

        //获取派车单ID
        $group_id = input('group_id');

        //获取派车单信息
        $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $group_id)->find();

        //判断派车单状态是否可以取消结算
        if ($dispatch_traveler_group['dispatch_group_status'] != 'accounts') {
            return ajax_return_error('此派车单当前状态不可进行取消结算操作');
        }

        if ($dispatch_traveler_group['is_settlement'] == '1') {
            return ajax_return_error('此派车单已结算成功，不可进行取消结算操作');
        }

        $data['is_apply_settlement'] = 0;

        $data['dispatch_group_status'] = 'achieve';

        $res = Db::name('dispatch_traveler_group')->strict(false)->where('id', $group_id)->update($data);

        if ($res) {
            return ajax_return_adv('取消结算成功');
        } else {
            return ajax_return_adv_error('取消结算失败');
        }

    }

    /**
     * 申请结算中
     * @author 颜东淦
     */
    public function account_applying()
    {
        $map['dtg.dispatch_group_status'] = 'accounts';
        $map['dtg.is_apply_settlement'] = '1';

        $data = input();
        if ($data['go_date']) {
            $map['dtg.go_date'] = array("between", [strtotime($data['go_date'] . " 00:00:00"), strtotime($data['go_date'] . " 23:59:59")]);

        }
        $url = '/admin/dispatch_traveler_group/in_proceed_html';
        if ($data) {
            foreach ($data as $dk => $dv) {
                if ($dk == $url) {
                    unset($data[$dk]);
                }
                if (!empty($dv)) {
                    $searchData[$dk] = $dv;
                }
            }
            $searchData['dispatch_group_status'] = 'accounts';
        } else {
            $searchData['dispatch_group_status'] = 'accounts';
        }
        if ($data['sales_id']) {
            $map['dtg.sales_id'] = array('in', $data['sales_id']);
        }
        //下单人
        if ($data['booking_people_name']) {
            $name['name'] = ['like', '%' . $data['booking_people_name'] . '%'];
            $travelPeople = Db::name('order_traveler')->where($name)->field('id,name,oid,group_id')->select();
            $travelPeopleIds = '';
            foreach ($travelPeople as $tpk => $tpv) {
                if (!empty($tpv['group_id'])) {
                    $travelPeopleIds .= $tpv['group_id'] . ',';
                }
            }
            $travelPeopleIds = rtrim($travelPeopleIds, ',');
            $map['dtg.id'] = ['in', $travelPeopleIds];
        }
        if ($data['dispatch_group_status']) {
            $map['dtg.dispatch_group_status'] = $data['dispatch_group_status'];
        }
        if ($data['car_form']) {
            $map['dtg.car_form'] = array('like', "%{$data['car_form']}%");
        }
        if ($data['remark']) {
            $map['dtg.remark'] = array('like', "%{$data['remark']}%");
        }
        if ($this::$isdelete) {
            $map['dtg.isdelete'] = 1;
        } else {
            $map['dtg.isdelete'] = 0;
        }
        if ($data['is_settlement'] || $data['is_settlement'] === "0") {
            $map['dtg.is_settlement'] = $data['is_settlement'];
        }
        if ($data['driver_user']) {
            $map['u.realname'] = array('like', "%{$data['driver_user']}%");
        }
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
        $list = Db::name('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_admin_user u', 'u.id=dtg.driver_user_id', 'left')
            ->field('dtg.*,u.realname')
            ->where($map)
            ->order("dtg.id desc")
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        $list_data = $list->toArray();
        if ($list_data['data']) {
            foreach ($list_data['data'] as $ldk => $ldv) {
                if ($ldv['is_pickup'] == '1') { //接机单
                    //查找客人姓名
                    $travelers = Db::name("order_traveler")
                        ->where('oid', $ldv['oid'])
                        ->select();
                } else {
                    //查找客人姓名
                    $travelers = Db::name("dispatch_traveler")->alias('dt')
                        ->join("tp_order_traveler ot", "ot.id=dt.traveler_id", "left")
                        ->where('dt.group_id', $ldv['id'])
                        ->field('ot.*')
                        ->select();
                }
                $booking_people_name = '';
                foreach ($travelers as $tk => $tv) {
                    $booking_people_name .= $tv['name'] . '+';
                }
                $booking_people_name = rtrim($booking_people_name, '+');
                $list_data['data'][$ldk]['booking_people_name'] = $booking_people_name;
                $list_data['data'][$ldk]['booking_people_num'] = count($travelers);
                $list_data['data'][$ldk]['route_title'] = Db::name('route')->where('id', $ldv['route_id'])->value('title');
                $driver = Db::name('driver')->where('id', $ldv['driver_user_id'])->field('driver_rank_id,vehicle_level')->find();
                $list_data['data'][$ldk]['driver_rank_id'] = $driver['driver_rank_id'];
                $list_data['data'][$ldk]['vehicle_level'] = $driver['vehicle_level'];
                if ($list_data['data'][$ldk]['is_reach_standard'] == '0') {
                    $list_data['data'][$ldk]['is_reach_standard'] = '否';
                } else {
                    $list_data['data'][$ldk]['is_reach_standard'] = '是';
                }
            }
        }
        $show = 1;
        $this->view->assign('list', $list);
        $this->view->assign('list_data', $list_data['data']);
        $this->view->assign('show', $show);
        $this->view->assign('searchCondition', $searchData);//搜索条件
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 批量结算（结算成功）
     * @return mixed
     * @author 颜东淦
     */
    public function batch_settlement()
    {
        $data = input();

        if (!isset($data['id'])) {
            return ajax_return_adv_error('没有选择派车单，请重试');
        }

        $success = 0;
        $error = 0;
        $error_id = [];

        foreach ($data['id'] as $k => $v) {

            $temp['id'] = $v;
            $temp['settlement_mode'] = $data['settlement_mode'];

            $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $temp['id'])->find();
//            halt($dispatch_traveler_group);
            //判断派车单状态
            if ($dispatch_traveler_group['dispatch_group_status'] != 'accounts') {
                $error += 1;
                $error_id[] = $v;
                continue;
            }

            if ($dispatch_traveler_group['is_apply_settlement'] != '1') {
                $error += 1;
                $error_id[] = $v;
                continue;
            }

            if ($dispatch_traveler_group['is_settlement'] == '1') {
                $error += 1;
                $error_id[] = $v;
                continue;
            }

            if ($dispatch_traveler_group['driver_user_id']) {
                //开启事务
                Db::startTrans();
                try {
                    $nowtime = time();
                    $update['dispatch_group_status'] = 'accounts';
                    $update['is_settlement'] = true;
                    $update['settlement_time'] = $nowtime;
                    $update['is_apply_settlement'] = 0;
                    $update['settlement_mode'] = $temp['settlement_mode'];
                    $update['settlement_money'] = $dispatch_traveler_group['this_settlement_money'];

                    $res = Db::name('dispatch_traveler_group')->where('id', $temp['id'])->update($update);

                    if ($res) {
                        $map['user_id'] = $dispatch_traveler_group['driver_user_id'];
                        $map['type'] = "checkouted";
                        $map['dispatch_traveler_group_id'] = $temp['id'];
                        // 增加司机的订单量
                        $driver_user_id = $dispatch_traveler_group['driver_user_id'];
                        $updateDriver = Db::name('driver')->where('user_id', $driver_user_id)->setInc('order_num'); // 订单量自增1
                        if ($updateDriver) {
                            Db::commit();
                            $notify = Db::name('notify')->where($map)->find();
                            if ($notify) {
                                $error += 1;
                                $error_id[] = $v;
                                continue;
                            }
                            //通知司机
                            $date_time = date("Y-m-d H:i:s", $nowtime);
                            set_info($dispatch_traveler_group['driver_user_id'], '已经结算', "{$date_time} 你的订单已经结算，派车单号为{$temp['id']},结算金额为{$temp['settlement_money']}", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $temp['id']));
                            $success += 1;
                        } else {
                            Db::rollback();
                            $error += 1;
                            $error_id[] = $v;
                            continue;
                        }
                    } else {
                        Db::rollback();
                        $error += 1;
                        $error_id[] = $v;
                        continue;
                    }
                } catch (\Exception $e) {
                    Db::rollback();
                    $error += 1;
                    $error_id[] = $v;
                    continue;
                }
            } else {
                $error += 1;
                $error_id[] = $v;
                continue;
            }
        }
        if (count($error_id) === 0) {
            $msg = '成功结算：' . $success . '条。失败结算' . $error . "条。";
        } else {
            $temp = implode(',', $error_id);
            $msg = '成功结算：' . $success . '条。失败结算' . $error . "条。失败的派车单ID为：" . $temp . "。";
        }
        return ajax_return_adv($msg);
    }

    /**
     * 确认结算（结算成功）
     * @return mixed
     * @author 颜东淦
     */
    public function confirm_settlement(Request $request)
    {
        if ($request->isAjax()) {

            $data = input();

            $rule = [
                'id' => 'require',
                'settlement_mode' => 'require',
            ];
            $msg = [
                'id.require' => '参数错误',
                'settlement_mode.require' => '结算方式不能为空',
            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                return ajax_return_error($validate->getError());
            }

            $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $data['id'])->find();

            //判断派车单状态
            if ($dispatch_traveler_group['dispatch_group_status'] != 'accounts') {
                return ajax_return_error('派车单当前状态不可结算');
            }

            if ($dispatch_traveler_group['is_apply_settlement'] != '1') {
                return ajax_return_error('请先申请结算');
            }

            if ($dispatch_traveler_group['is_settlement'] == '1') {
                return ajax_return_error('该派车单已结算');
            }

            if ($dispatch_traveler_group['driver_user_id']) {
                //开启事务
                Db::startTrans();
                try {
                    $nowtime = time();
                    $update['dispatch_group_status'] = 'accounts';
                    $update['is_settlement'] = true;
                    $update['settlement_time'] = $nowtime;
                    $update['is_apply_settlement'] = 0;
                    $update['settlement_mode'] = $data['settlement_mode'];
                    $update['settlement_money'] = $dispatch_traveler_group['this_settlement_money'];

                    $res = Db::name('dispatch_traveler_group')->where('id', $data['id'])->update($update);

                    if ($res) {
                        $map['user_id'] = $dispatch_traveler_group['driver_user_id'];
                        $map['type'] = "checkouted";
                        $map['dispatch_traveler_group_id'] = $data['id'];
                        // 增加司机的订单量
                        $driver_user_id = $dispatch_traveler_group['driver_user_id'];
                        $updateDriver = Db::name('driver')->where('user_id', $driver_user_id)->setInc('order_num'); // 订单量自增1
                        if ($updateDriver) {
                            Db::commit();
                            $notify = Db::name('notify')->where($map)->find();
                            if ($notify) {
                                return ajax_return_error('已经通知过');
                            }
                            //通知司机
                            $date_time = date("Y-m-d H:i:s", $nowtime);
                            set_info($dispatch_traveler_group['driver_user_id'], '已经结算', "{$date_time} 你的订单已经结算，派车单号为{$data['id']},结算金额为{$data['settlement_money']}", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $data['id']));
                            return ajax_return_adv('结算成功');
                        } else {
                            Db::rollback();
                            return ajax_return_adv_error('结算失败');
                        }
                    } else {
                        Db::rollback();
                        return ajax_return_adv_error('结算失败');
                    }
                } catch (\Exception $e) {
                    Db::rollback();
                    return ajax_return_adv_error($e->getMessage());
                }
            } else {
                return ajax_return_error('未分配司导');
            }
        } else {
            $id = input('group_id');
            $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $id)->find();
            $this->view->assign('vo', $dispatch_traveler_group);
            return $this->view->fetch();
        }
    }

    /**
     * 批量驳回
     * @author 颜东淦
     */
    public function batch_refuse()
    {
        $data = input();

        if (!isset($data['id'])) {
            return ajax_return_adv_error('没有选择派车单，请重试');
        }

        $success = 0;
        $error = 0;
        $error_id = [];

        foreach ($data['id'] as $k => $v) {

            $temp['id'] = $v;
            $temp['reject_settlement_reason'] = $data['reject_settlement_reason'];

            $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $temp['id'])->find();

            //判断派车单状态
            if ($dispatch_traveler_group['dispatch_group_status'] != 'accounts' || $dispatch_traveler_group['is_apply_settlement'] != '1') {
                $error += 1;
                $error_id[] = $v;
                continue;
            }

            if ($dispatch_traveler_group['is_settlement'] == '1') {
                $error += 1;
                $error_id[] = $v;
                continue;
            }

            if ($dispatch_traveler_group['driver_user_id']) {
                $nowtime = time();

                $update['dispatch_group_status'] = 'accounts';
                $update['is_settlement'] = false;
                $update['reject_settlement_time'] = $nowtime;
                $update['is_reject_settlement'] = true;
                $update['reject_settlement_reason'] = $temp['reject_settlement_reason'];
                $update['is_apply_settlement'] = 0;

                $res = Db::name('dispatch_traveler_group')->where('id', $temp['id'])->update($update);

                if ($res) {
                    $map['user_id'] = $dispatch_traveler_group['driver_user_id'];
                    $map['type'] = "reject_settlement";
                    $map['dispatch_traveler_group_id'] = $temp['id'];
                    $notify = Db::name('notify')->where($map)->find();
                    if ($notify) {
                        $error += 1;
                        $error_id[] = $v;
                        continue;
                    }
                    $date_time = date("Y-m-d H:i:s", $nowtime);
                    set_info($dispatch_traveler_group['driver_user_id'], '订单结算不通过', "{$date_time} 你的订单结算不通过，订单编号为{$temp['id']},结算金额为{$dispatch_traveler_group['settlement_money']}", 'reject_settlement', array('dispatch_traveler_group_id' => $temp['id']));
                    $success += 1;
                } else {
                    $error += 1;
                    $error_id[] = $v;
                    continue;
                }
            } else {
                $error += 1;
                $error_id[] = $v;
                continue;
            }
        }

        if (count($error_id) === 0) {
            $msg = '成功驳回：' . $success . '条。失败驳回' . $error . "条。";
        } else {
            $temp = implode(',', $error_id);
            $msg = '成功驳回：' . $success . '条。失败驳回' . $error . "条。失败的派车单ID为：" . $temp . "。";
        }
        return ajax_return_adv($msg);
    }

    /**
     * 拒绝结算
     * @author 颜东淦
     */
    public function refuse_settlement(Request $request)
    {
        if ($request->isAjax()) {
            $data = input();

            $rule = [
                'id' => 'require',
                'reject_settlement_reason' => 'require',
            ];
            $msg = [
                'id.require' => '参数错误',
                'reject_settlement_reason.require' => '拒绝原因不能为空',
            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                return ajax_return_error($validate->getError());
            }

            $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $data['id'])->find();

            //判断派车单状态
            if ($dispatch_traveler_group['dispatch_group_status'] != 'accounts' || $dispatch_traveler_group['is_apply_settlement'] != '1') {
                return ajax_return_error('派车单当前状态不为申请结算，不可进行拒绝结算操作');
            }

            if ($dispatch_traveler_group['is_settlement'] == '1') {
                return ajax_return_error('该派车单已结算');
            }

            if ($dispatch_traveler_group['driver_user_id']) {
                $nowtime = time();

                $update['dispatch_group_status'] = 'accounts';
                $update['is_settlement'] = false;
                $update['reject_settlement_time'] = $nowtime;
                $update['is_reject_settlement'] = true;
                $update['reject_settlement_reason'] = $data['reject_settlement_reason'];
                $update['is_apply_settlement'] = 0;

                $res = Db::name('dispatch_traveler_group')->where('id', $data['id'])->update($update);

                if ($res) {
                    $map['user_id'] = $dispatch_traveler_group['driver_user_id'];
                    $map['type'] = "reject_settlement";
                    $map['dispatch_traveler_group_id'] = $data['id'];
                    $notify = Db::name('notify')->where($map)->find();
                    if ($notify) {
                        return ajax_return_error('已经通知过司机');
                    }
                    $date_time = date("Y-m-d H:i:s", $nowtime);
                    set_info($dispatch_traveler_group['driver_user_id'], '订单结算不通过', "{$date_time} 你的订单结算不通过，订单编号为{$data['id']},结算金额为{$dispatch_traveler_group['settlement_money']}", 'reject_settlement', array('dispatch_traveler_group_id' => $data['id']));
                    return ajax_return_adv('拒绝结算成功');
                } else {
                    return ajax_return_error('拒绝结算失败');
                }
            } else {
                return ajax_return_error('未分配司导');
            }

        } else {
            $id = input('group_id');
            $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $id)->find();
            $this->view->assign('vo', $dispatch_traveler_group);
            return $this->view->fetch();
        }


    }

    /**
     * 已结算
     * @author 颜东淦
     */
    public function in_accounts()
    {

        $map['dtg.dispatch_group_status'] = 'accounts';
        $map['dtg.is_settlement'] = '1';
        $map['dtg.isdelete'] = '0';

        $data = input();
        if ($data['go_date']) {
            $map['dtg.go_date'] = array("between", [strtotime($data['go_date'] . " 00:00:00"), strtotime($data['go_date'] . " 23:59:59")]);

        }
        $url = '/admin/dispatch_traveler_group/in_proceed_html';
        if ($data) {
            foreach ($data as $dk => $dv) {
                if ($dk == $url) {
                    unset($data[$dk]);
                }
                if (!empty($dv)) {
                    $searchData[$dk] = $dv;
                }
            }
            $searchData['dispatch_group_status'] = 'accounts';
        } else {
            $searchData['dispatch_group_status'] = 'accounts';
        }
        if ($data['sales_id']) {
            $map['dtg.sales_id'] = array('in', $data['sales_id']);
        }
        //下单人
        if ($data['booking_people_name']) {
            $name['name'] = ['like', '%' . $data['booking_people_name'] . '%'];
            $travelPeople = Db::name('order_traveler')->where($name)->field('id,name,oid,group_id')->select();
            $travelPeopleIds = '';
            foreach ($travelPeople as $tpk => $tpv) {
                if (!empty($tpv['group_id'])) {
                    $travelPeopleIds .= $tpv['group_id'] . ',';
                }
            }
            $travelPeopleIds = rtrim($travelPeopleIds, ',');
            $map['dtg.id'] = ['in', $travelPeopleIds];
        }
        if ($data['dispatch_group_status']) {
            $map['dtg.dispatch_group_status'] = $data['dispatch_group_status'];
        }
        if ($data['car_form']) {
            $map['dtg.car_form'] = array('like', "%{$data['car_form']}%");
        }
        if ($data['remark']) {
            $map['dtg.remark'] = array('like', "%{$data['remark']}%");
        }
//        if($this::$isdelete){
//            $map['dtg.isdelete']=1;
//        }else{
//            $map['dtg.isdelete']=0;
//        }
        if ($data['is_settlement'] || $data['is_settlement'] === "0") {
            $map['dtg.is_settlement'] = $data['is_settlement'];
        }
        if ($data['driver_user']) {
            $map['u.realname'] = array('like', "%{$data['driver_user']}%");
        }
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
        $list = Db::name('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_admin_user u', 'u.id=dtg.driver_user_id', 'left')
            ->field('dtg.*,u.realname')
            ->where($map)
            ->order("dtg.id desc")
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        $list_data = $list->toArray();
        if ($list_data['data']) {
            foreach ($list_data['data'] as $ldk => $ldv) {
                if ($ldv['is_pickup'] == '1') { //接机单
                    //查找客人姓名
                    $travelers = Db::name("order_traveler")
                        ->where('oid', $ldv['oid'])
                        ->select();
                } else {
                    //查找客人姓名
                    $travelers = Db::name("dispatch_traveler")->alias('dt')
                        ->join("tp_order_traveler ot", "ot.id=dt.traveler_id", "left")
                        ->where('dt.group_id', $ldv['id'])
                        ->field('ot.*')
                        ->select();
                }
                $booking_people_name = '';
                foreach ($travelers as $tk => $tv) {
                    $booking_people_name .= $tv['name'] . '+';
                }
                $booking_people_name = rtrim($booking_people_name, '+');
                $list_data['data'][$ldk]['booking_people_name'] = $booking_people_name;
                $list_data['data'][$ldk]['booking_people_num'] = count($travelers);
                $list_data['data'][$ldk]['route_title'] = Db::name('route')->where('id', $ldv['route_id'])->value('title');
                $driver = Db::name('driver')->where('id', $ldv['driver_user_id'])->field('driver_rank_id,vehicle_level')->find();
                $list_data['data'][$ldk]['driver_rank_id'] = $driver['driver_rank_id'];
                $list_data['data'][$ldk]['vehicle_level'] = $driver['vehicle_level'];
                if ($list_data['data'][$ldk]['is_reach_standard'] == '0') {
                    $list_data['data'][$ldk]['is_reach_standard'] = '否';
                } else {
                    $list_data['data'][$ldk]['is_reach_standard'] = '是';
                }
            }
        }
        $show = 1;
        $this->view->assign('list', $list);
        $this->view->assign('list_data', $list_data['data']);
        $this->view->assign('show', $show);
        $this->view->assign('searchCondition', $searchData);//搜索条件
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 结算驳回
     * @author 颜东淦
     */
    public function settlement_dismiss()
    {

        $map['dtg.dispatch_group_status'] = 'accounts';
        $map['dtg.is_reject_settlement'] = '1';

        $data = input();
        if ($data['go_date']) {
            $map['dtg.go_date'] = array("between", [strtotime($data['go_date'] . " 00:00:00"), strtotime($data['go_date'] . " 23:59:59")]);

        }
        $url = '/admin/dispatch_traveler_group/in_proceed_html';
        if ($data) {
            foreach ($data as $dk => $dv) {
                if ($dk == $url) {
                    unset($data[$dk]);
                }
                if (!empty($dv)) {
                    $searchData[$dk] = $dv;
                }
            }
            $searchData['dispatch_group_status'] = 'accounts';
        } else {
            $searchData['dispatch_group_status'] = 'accounts';
        }
        if ($data['sales_id']) {
            $map['dtg.sales_id'] = array('in', $data['sales_id']);
        }
        //下单人
        if ($data['booking_people_name']) {
            $name['name'] = ['like', '%' . $data['booking_people_name'] . '%'];
            $travelPeople = Db::name('order_traveler')->where($name)->field('id,name,oid,group_id')->select();
            $travelPeopleIds = '';
            foreach ($travelPeople as $tpk => $tpv) {
                if (!empty($tpv['group_id'])) {
                    $travelPeopleIds .= $tpv['group_id'] . ',';
                }
            }
            $travelPeopleIds = rtrim($travelPeopleIds, ',');
            $map['dtg.id'] = ['in', $travelPeopleIds];
        }
        if ($data['dispatch_group_status']) {
            $map['dtg.dispatch_group_status'] = $data['dispatch_group_status'];
        }
        if ($data['car_form']) {
            $map['dtg.car_form'] = array('like', "%{$data['car_form']}%");
        }
        if ($data['remark']) {
            $map['dtg.remark'] = array('like', "%{$data['remark']}%");
        }
        if ($this::$isdelete) {
            $map['dtg.isdelete'] = 1;
        } else {
            $map['dtg.isdelete'] = 0;
        }
        if ($data['is_settlement'] || $data['is_settlement'] === "0") {
            $map['dtg.is_settlement'] = $data['is_settlement'];
        }
        if ($data['driver_user']) {
            $map['u.realname'] = array('like', "%{$data['driver_user']}%");
        }
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
        $list = Db::name('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_admin_user u', 'u.id=dtg.driver_user_id', 'left')
            ->field('dtg.*,u.realname')
            ->where($map)
            ->order("dtg.id desc")
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        $list_data = $list->toArray();
        if ($list_data['data']) {
            foreach ($list_data['data'] as $ldk => $ldv) {
                if ($ldv['is_pickup'] == '1') { //接机单
                    //查找客人姓名
                    $travelers = Db::name("order_traveler")
                        ->where('oid', $ldv['oid'])
                        ->select();
                } else {
                    //查找客人姓名
                    $travelers = Db::name("dispatch_traveler")->alias('dt')
                        ->join("tp_order_traveler ot", "ot.id=dt.traveler_id", "left")
                        ->where('dt.group_id', $ldv['id'])
                        ->field('ot.*')
                        ->select();
                }
                $booking_people_name = '';
                foreach ($travelers as $tk => $tv) {
                    $booking_people_name .= $tv['name'] . '+';
                }
                $booking_people_name = rtrim($booking_people_name, '+');
                $list_data['data'][$ldk]['booking_people_name'] = $booking_people_name;
                $list_data['data'][$ldk]['booking_people_num'] = count($travelers);
                $list_data['data'][$ldk]['route_title'] = Db::name('route')->where('id', $ldv['route_id'])->value('title');
                $driver = Db::name('driver')->where('id', $ldv['driver_user_id'])->field('driver_rank_id,vehicle_level')->find();
                $list_data['data'][$ldk]['driver_rank_id'] = $driver['driver_rank_id'];
                $list_data['data'][$ldk]['vehicle_level'] = $driver['vehicle_level'];
                if ($list_data['data'][$ldk]['is_reach_standard'] == '0') {
                    $list_data['data'][$ldk]['is_reach_standard'] = '否';
                } else {
                    $list_data['data'][$ldk]['is_reach_standard'] = '是';
                }
            }
        }
        $show = 1;
        $this->view->assign('list', $list);
        $this->view->assign('list_data', $list_data['data']);
        $this->view->assign('show', $show);
        $this->view->assign('searchCondition', $searchData);//搜索条件
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 删除派车单
     * @author 颜东淦
     */
    public function dispatch_delete()
    {
        $group_id = input('id');

        $dispatch_traveler_group = Db::name('dispatch_traveler_group')->strict(false)->where('id', $group_id)->field('id,isdelete,dispatch_group_status,is_settlement')->find();

        if ($dispatch_traveler_group['dispatch_group_status'] != 'accounts') {
            return ajax_return_adv_error('该派车单当前状态不可删除');
        }

        if ($dispatch_traveler_group['is_settlement'] != 1) {
            return ajax_return_adv_error('该派车单当前状态不可删除');
        }

        if ($dispatch_traveler_group['isdelete'] == '1') {
            return ajax_return_adv_error('该派车单已删除');
        }

        $data['isdelete'] = 1;

        $res = Db::name('dispatch_traveler_group')->strict(false)->where('id', $group_id)->update($data);

        if ($res) {
            return ajax_return_adv('删除成功');
        } else {
            return ajax_return_adv_error('删除失败');
        }
    }

    /**
     * 编辑派车单
     * @return mixed
     */
    public function dispatch_edit($id)
    {
        if (!$this->request->isAjax()) {
            $group_id = input('id');
            $group = Db::name('dispatch_traveler_group')->where(array('id' => $group_id))->find();
            $day = Db::name('route')->where('id', $group['route_id'])->value('day');
            $driver_users = Db::name('driver')->alias('d')
                ->join('tp_admin_user u', 'u.id=d.user_id', 'left')
                ->field("u.*")
                ->select();
            $this->view->assign("vo", $group);
            $this->view->assign("driver_users", $driver_users);
            $this->view->assign("day", $day);
            $car_types = Db::name('car_type')->select();
            $this->view->assign("car_types", $car_types);

            return $this->view->fetch();
        } else {
            $input = input();

            $input['go_date'] = strtotime($input['go_date']);
            $input['end_date'] = strtotime($input['end_date']);
            $group = $input;

            if (!empty($group['go_date']) && !empty($group['end_date']) && ($group['go_date'] > $group['end_date'])) {
                return ajax_return_adv_error('订单的开始日期不能大于结束日期');
            }

            $res = Db::name('dispatch_traveler_group')->strict(false)->where('id', $group['id'])->update($group);

            if ($res) {
                return ajax_return_adv('编辑成功');
            } else {
                return ajax_return_adv_error('编辑失败');
            }
        }

    }

    /**
     * 添加派车单备注列表
     * @return mixed
     */
    public function add_dispatch_remark()
    {
        $data = input();

        $realname = Db::name('admin_user_info')
            ->where('id', UID)
            ->value('realname');

        if (UID === 1) {
            $role = '超级管理员';
        } else {
            $role = Db::name('admin_role_user')
                ->alias('aru')
                ->join('tp_admin_role ar', 'ar.id=aru.role_id', 'left')
                ->where('aru.user_id', UID)
                ->value('ar.name');
        }

        $result = Db::name('dispatch_remark')
            ->insert([
                'dtg_id' => $data['dtg_id'],
                'realname' => $realname,
                'role' => $role,
                'content' => $data['remark'],
                'create_time' => time()
            ]);

        if ($result) {
            return ajax_return_adv("添加成功");
        } else {
            return ajax_return_adv_error('添加失败');
        }
    }

    /**
     * 查看派车单备注列表
     * @return mixed
     */
    public function dispatch_remark()
    {
        $data = input();

        $result = Db::name('dispatch_remark')
            ->where('dtg_id', $data['dtg_id'])
            ->order('id desc')
            ->select();

        $this->view->assign('list', $result);
        return $this->view->fetch();
    }

    /**
     * 好评奖励
     * @return mixed
     */
    public function good_reward(Request $request)
    {
        $data = input();

        if (!$data['group_id']) {
            return ajax_return_adv_error('缺少参数id');
        }

        $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $data['group_id'])->find();

        if ($request->isAjax()) {
            //校验数据
            $rule = [
                'group_id' => 'require',
                'award' => 'require|number',
            ];
            $msg = [
                'group_id.require' => '参数错误',
                'award.require' => '请填写好评奖励金额',
                'award.number' => '好评奖励金额格式填写错误，请输入数字',
            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                return ajax_return_error($validate->getError());
            }

            if ($data['is_apply_good_reward'] == 1) {//已申请好评奖励

                $good_reward_info = Db::name('driver_good_reputation')->where('dispatch_group_id', $data['group_id'])->find();

                if (!$good_reward_info) {
                    return ajax_return_adv_error('不存在此记录');
                }

                if ($good_reward_info['status'] == 1) {
                    return ajax_return_adv_error('该好评奖励已结算成功，不可进行修改');
                }

                if ($data['status'] != $good_reward_info['status']) {
                    return ajax_return_adv_error('状态有误，请重新刷新页面');
                }

                if ($data['status'] == 0 || $data['status'] == 2) {//结算驳回再次申请 //申请结算中，修改信息
                    $res = Db::name('driver_good_reputation')
                        ->strict(false)
                        ->where('dispatch_group_id', $data['group_id'])
                        ->update(array('award' => $data['award'], 'remark' => $data['remark'], 'status' => 2));
                    if ($res) {
                        return ajax_return_adv("操作成功");
                    } else {
                        return ajax_return_adv_error('操作失败');
                    }
                } else {
                    return ajax_return_adv_error('状态有误，请重新刷新页面');
                }

            } else {//未申请好评奖励

                //查询司机银行卡信息
                $bank_card = Db::name('bank_card')->where('user_id', $dispatch_traveler_group['driver_user_id'])->find();
                if (!$bank_card) {
                    return ajax_return_adv_error('该司机缺少银行卡信息，请先进行完善');
                }

                $ck = Db::name('driver_good_reputation')->where('dispatch_group_id', $data['group_id'])->find();
                if ($ck) {
                    return ajax_return_adv_error('已申请过，无需重复申请');
                }

                $insert_data = [
                    'dispatch_group_id' => $data['group_id'],
                    'bank_name' => $bank_card['bank_name'],
                    'card_num' => $bank_card['card_num'],
                    'user_name' => $bank_card['user_name'],
                    'award' => $data['award'],
                    'apply_time' => time(),
                    'status' => 2,
                    'remark' => $data['remark'],
                ];

                Db::startTrans();
                try {
                    $res = Db::name('driver_good_reputation')->strict(false)->insert($insert_data);

                    if ($res) {
                        $group_res = Db::name('dispatch_traveler_group')->where('id', $data['group_id'])->update(array('is_apply_good_reward' => 1));
                        if ($group_res) {
                            Db::commit();
                            return ajax_return_adv("申请成功");
                        } else {
                            Db::rollback();
                            return ajax_return_adv_error('申请失败');
                        }

                    } else {
                        Db::rollback();
                        return ajax_return_adv_error('申请失败');
                    }
                } catch (\Exception $e) {
                    Db::rollback();
                    return ajax_return_adv_error($e->getMessage());
                }

            }
        } else {
            if ($dispatch_traveler_group['is_apply_good_reward'] == 1) {//已申请好评奖励
                $data = Db::name('driver_good_reputation')->where('dispatch_group_id', $data['group_id'])->find();
                if (!$data) {
                    return ajax_return_adv_error('不存在此记录');
                }
                $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id', $data['dispatch_group_id'])->find();

                $data['realname'] = Db::name('admin_user')->where('id', $dispatch_traveler_group['driver_user_id'])->value('realname');
                $driver_type = Db::name('driver')->where('user_id', $dispatch_traveler_group['driver_user_id'])->value('driver_type');
                $data['driver_type'] = Db::name('driver_type')->where('id', $driver_type)->value('name');
                $data['route_title'] = Db::name('route')->where('id', $dispatch_traveler_group['route_id'])->value('title');
                $data['accumulative_award'] = Db::name('driver')->where('user_id', $dispatch_traveler_group['driver_user_id'])->value('accumulative_award');
                $this->view->assign('data', $data);
                $this->view->assign('is_apply_good_reward', 1);
                return $this->view->fetch();

            } else {//未申请好评奖励
                $this->view->assign('data', $data);
                $this->view->assign('is_apply_good_reward', 0);
                return $this->view->fetch();
            }
        }
    }

    /**
     * 预支付
     * @return mixed
     */
    public function prepayment(Request $request)
    {
        $data = input();
        if ($request->isAjax()) {
            //校验数据
            $rule = [
                'group_id' => 'require|number',
                'prepaid_expenses' => 'require|number',
                'end_gauge_value' => 'require|number',
                'end_odometer_value' => 'require|number',
            ];
            $msg = [
                'group_id.require' => '参数有误',
                'group_id.number' => '参数格式有误',
                'prepaid_expenses.require' => '预支付标准不能为空',
                'prepaid_expenses.number' => '预支付标准格式填写错误，请输入数字',
                'end_gauge_value.require' => '结束油表不能为空',
                'end_gauge_value.number' => '结束油表格式填写错误，请输入数字',
                'end_odometer_value.require' => '结束里程不能为空',
                'end_odometer_value.number' => '结束里程格式填写错误，请输入数字',
            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                return ajax_return_error($validate->getError());
            }

            $res = Db::name('dispatch_traveler_group')->strict(false)->where('id', $data['group_id'])->update($data);
            if ($res) {
                return ajax_return_adv('修改成功');
            } else {
                return ajax_return_adv_error('修改失败');
            }
        } else {
            if (!$data['group_id']) {
                return ajax_return_adv_error('缺少参数id');
            }

            $list = Db::name('driver_prepayment')
                ->alias('dp')
                ->join('tp_dispatch_traveler_group dtg', 'dtg.id=dp.group_id', 'left')
                ->join('tp_route r', 'r.id=dtg.route_id', 'left')
                ->join('tp_driver d', 'd.user_id=dtg.driver_user_id', 'left')
                ->join('tp_admin_user au', 'au.id=dtg.driver_user_id', 'left')
                ->field('dp.*,dtg.go_date,dtg.route_id,dtg.driver_user_id,dtg.prepaid_expenses,dtg.end_gauge_value,dtg.start_gauge_value,dtg.end_odometer_value,dtg.start_odometer_value,r.title,r.day,d.car_type,au.realname')
                ->where('group_id', $data['group_id'])
                ->order('dp.id desc')
                ->find();

            // 获取发票费用

            $list['invoice'] = Db::name('driver_invoice')
                ->where('dispatch_group_id', $data['group_id'])
                ->select();

//            dump($list);

            $list['oil_cost'] = 0;
            $list['rests_cost'] = 0;
            $list['parking_fee'] = 0;
            $list['car_washing_fee'] = 0;
            $list['road_toll'] = 0;
            foreach ($list['invoice'] as $k2 => $v2) {
                switch ($v2['invoice_type']) {
                    case '加油费':
                        $list['oil_cost'] = $v2['total'];
                        break;
                    case '停车费':
                        $list['parking_fee'] = $v2['total'];
                        break;
                    case '洗车费':
                        $list['car_washing_fee'] = $v2['total'];
                        break;
                    case '过路费':
                        $list['road_toll'] = $v2['total'];
                        break;
                    default:
                        $list['rests_cost'] = $v2['total'] + $list['rests_cost'];
                        break;
                }
            }


//            $info = Db::name('driver_prepayment')->where('group_id',$data['group_id'])->find();
//            if(!$info){
//                $info = [];
//            }
//            $group_info = Db::name('dispatch_traveler_group')->where('id',$data['group_id'])->field('id as group_id,prepaid_expenses,end_gauge_value,end_odometer_value,driver_user_id,route_id,go_date,end_date')->find();
//            $list = array_merge($info,$group_info);
            $this->view->assign('list', $list);
            return $this->view->fetch();
        }
    }

    /**
     * 检查是否填写
     * @author 颜东淦
     */
    public function ck_fill($name, $tip_name)
    {
        if (empty($name)) {
            return '未填写' . $tip_name;
        } else {
            return $name;
        }
    }

//    public function send_driver01(Request $request)
//    {
//        $input=input();
//        $group_id=$input['group_id'];
//        if(!$this->request->isAjax()){
//            if($input['realname']){
//                $map['u.realname']=array('like',"%{$input['realname']}%");
//            }
//            if($input['mobile']){
//                $map['u.account']=array('like',"%{$input['mobile']}%");
//            }
//            if($input['seats']){
//                $map['d.seats']=$input['seats'];
//            }
//            if($input['car_type']){
//                $map['d.car_type']=array('like',"%{$input['car_type']}%");
//            }
//            if($input['car_model']){
//                $map['d.car_model']=array('like',"%{$input['car_model']}%");
//            }
//            if($input['car_brand']){
//                $map['d.car_brand']=array('like',"%{$input['car_brand']}%");
//            }
//            if($input['driver_rank_id']){
//                if ($input['driver_rank_id'] == 5){
//                    $map['d.driver_rank_id']=0;
//                }else{
//                    $map['d.driver_rank_id']=$input['driver_rank_id'];
//                }
//
//            }
//            if($input['tag']){
//                $map['d.tag']=array('like',"%{$input['tag']}%");
//            }
//            if ($input['nationality']){
//                $map['d.nationality'] = ['like',"%{$input['nationality']}%"];
//            }
////            $map['d.inservice']=false;
////            $group=Db::name('dispatch_traveler_group')->where(array('id'=>$group_id))->find();
////            $driver_users=Db::name('driver')->alias('d')
////                ->join('tp_admin_user u','u.id=d.user_id','left')
////                ->join("tp_driver_rank r", "r.id=d.driver_rank_id", "left")
////                ->where('isagree',1)
////                ->where($map)
////                ->field("u.*,d.*,r.name as r_name")
////                ->select();
////            $map['d.inservice'] = 1;
////            //服务中的司机
////            $drivers_in_service = Db::name('driver')->alias('d')
////                ->join('tp_admin_user u','u.id=d.user_id','left')
////                ->join("tp_driver_rank r", "r.id=d.driver_rank_id", "left")
////                ->where('isagree',1)
////                ->where($map)
////                ->field("u.*,d.*,r.name as r_name")
////                ->select();
////            //司机已经有两个单的过滤掉
////            $driverUserIds = '';//服务中司机id
////            foreach ($drivers_in_service as $disk=>$disv){
////                $driverUserIds .= $disv['user_id'].',';
////            }
////            $driverUserIds = rtrim($driverUserIds,',');
////            $driverUsers = Db::name('dispatch_traveler_group')->where('driver_user_id','in',$driverUserIds)
////                                                ->field('id,dispatch_id,driver_user_id,go_date,end_date,dispatch_group_status')->select();
////            $sql = Db::name('dispatch_traveler_group')->where('driver_user_id','in',$driverUserIds)
////                ->field('id,dispatch_id,driver_user_id,go_date,end_date,dispatch_group_status')->fetchSql(true)->select();
////            //去掉未分配、已完成、已结算
////            foreach ($driverUsers as $dik=>$div){
////                if ($div['dispatch_group_status']=='undistributed' ||$div['dispatch_group_status']=='accounts' || $div['dispatch_group_status']=='achieve'){
////                    unset($driverUsers[$dik]);
////                }
////            }
////            //
////            $driverUserIds = explode(',',$driverUserIds);
////            $driverArr = [];
////            foreach ($driverUsers as $duk=>$duv){
////                if (in_array($duv['driver_user_id'],$driverUserIds)){
////                    $driverArr[$duv['driver_user_id']][] = $duv;
////                }
////            }
////            foreach ($drivers_in_service as $kkk=>$vvv){
////                //去掉已有两个单的司机
////                foreach ($driverArr as $dak=>$dav){
////                    $davCount = count($dav);
////                    if ($vvv['user_id'] == $dak && $davCount >= 2){
////                        unset($drivers_in_service[$kkk]);
////                    }elseif ($vvv['user_id'] == $dak && empty($dav[0]['end_date'])){
////                        //去掉司机上个订单没有结束时间
////                        unset($drivers_in_service[$kkk]);
////                    }elseif ($vvv['user_id'] == $dak && $dav[0]['end_date'] > $group['go_date']){
////                        //去掉结束时间高于分配订单的出发时间
////                        unset($drivers_in_service[$kkk]);
////                    }
////                }
////            }
//            $data = input();
//            //验证数据
//            if (!$data['group_id']){
//                return ajax_return_adv_error('缺少参数');
//            }
//            //查找该分配订单数据
//            $dispathOrder = Db::name('dispatch_traveler_group')->where('id',$data['group_id'])->find();
////            dump($data);;die;
//            if (empty($dispathOrder)){
//                return ajax_return_adv_error('不存在该派单数据');
//            }
//            $driver = Db::name('driver')->alias('d')->where('d.inservice',0)
//                ->join('tp_admin_user u','u.id=d.user_id')
//                ->where($map)
//                ->order('d.id','desc')
//                ->field('car_brand,car_model,car_brand_id,car_model_id,arctic_id,user_id,seats,car_type,driver_rank_id,inservice,tag,nationality')->select();
//
//            //从分配单中查找处于派单的分组
//            $dispatchSendOrder = Db::name('dispatch_traveler_group')
//                ->where('dispatch_group_status','sendorders')
//                ->field('driver_user_id,go_date,end_date')->select();
//            // 过滤不在服务中的处于派单的司机
//            foreach ($driver as $index => $item) {
//                foreach ($dispatchSendOrder as $index0 => $item0) {
//                    if ($item['user_id'] == $item0['driver_user_id']){
//                        unset($driver[$index]);
//                    }
//                }
//                //查找不在服务状态的司机用户信息
//                $driverInservice = Db::name('admin_user')->where('id',$item['user_id'])->find();
//                if ($driverInservice){
//                    $driver[$index]['realname'] = $driverInservice['realname'];
//                    $driver[$index]['account'] = $driverInservice['account'];
//                }else{
//                    $driver[$index]['realname'] = '该司机的用户信息已被删除';
//                    $driver[$index]['account'] = '该司机的账号信息已被删除';
//                }
//                //查找该司机的等级
//                $driverRank = Db::name('driver_rank')->where('id',$item['driver_rank_id'])->find();
//                if ($driverRank){
//                    $driver[$index]['r_name'] = $driverRank['name'];
//                }else{
//                    $driver[$index]['r_name'] = '新手';
//                }
//            }
//            //处理派单中的司机
//            foreach ($dispatchSendOrder as $dsok=>$dsov){
//                //过滤处于派单状态，但派单的结束时间为0或空的司机
//                if (!$dsov['end_date']){
//                    unset($dispatchSendOrder[$dsok]);
//                    continue;
//                }
//                //过滤结束时间大于下一个派单的开始时间
//                if ($dsov['end_date'] > $dispathOrder['go_date']){
//                    unset($dispatchSendOrder[$dsok]);
//                    continue;
//                }
//                //根据用户id查找司机的用户名
//                $driverUserInfo = Db::name('admin_user')->where('id',$dsov['driver_user_id'])->find();
//                if ($driverUserInfo){
//                    $dispatchSendOrder[$dsok]['realname'] = $driverUserInfo['realname'];
//                    $dispatchSendOrder[$dsok]['account'] = $driverUserInfo['account'];
//                }else{
//                    $dispatchSendOrder[$dsok]['realname'] = '该司机的用户信息已被删除';
//                }
//                //查找当前的司机信息
//                $driverData = Db::name('driver')->alias('d')
//                    ->join('tp_admin_user u','u.id=d.user_id','left')
//                    ->where($map)
//                    ->where('d.inservice',1)
//                    ->where('user_id',$dsov['driver_user_id'])
//                    ->order('d.id','desc')
//                    ->field('car_brand,car_model,car_brand_id,car_model_id,arctic_id,user_id,seats,car_type,driver_rank_id,inservice,tag,nationality')->find();
//                if ($driverData) {
//                    $dispatchSendOrder[$dsok]['seats'] = $driverData['seats'];
//                    $dispatchSendOrder[$dsok]['car_type'] = $driverData['car_type'];
//                    $dispatchSendOrder[$dsok]['driver_rank_id'] = $driverData['driver_rank_id'];
//                    $dispatchSendOrder[$dsok]['inservice'] = $driverData['inservice'];
//                    $dispatchSendOrder[$dsok]['tag'] = $driverData['tag'];
//                    $dispatchSendOrder[$dsok]['nationality'] = $driverData['nationality'];
//                }else{
//                    unset($dispatchSendOrder[$dsok]);
//                    continue;
//                }
//                //查找该司机的等级
//                $driverRank = Db::name('driver_rank')->where('id',$driverData['driver_rank_id'])->find();
//                if ($driverRank){
//                    $dispatchSendOrder[$dsok]['r_name'] = $driverRank['name'];
//                }else{
//                    $dispatchSendOrder[$dsok]['r_name'] = '新手';
//                }
//                //过滤有两个订单的司机：进行中或已派单
//                $sendCount = Db::name('dispatch_traveler_group')->where('driver_user_id',$dsov['driver_user_id'])
//                    ->where('dispatch_group_status','in','sendorders,proceed')
//                    ->count();
//                if ($sendCount >= 2){
//                    unset($dispatchSendOrder[$dsok]);
//                }
//            }
//            $dispatchProceedOrder = Db::name('dispatch_traveler_group')->where('dispatch_group_status','proceed')
//                ->field('driver_user_id,go_date,end_date')->select();
//            //处理进行中的司机
//            foreach ($dispatchProceedOrder as $index2 => $item2) {
//                //过滤处于服务中状态的，但派单时间为空的司机
//                if (!$item2['end_date']){
//                    unset($dispatchProceedOrder[$index2]);
//                    continue;
//                }
//                //过滤结束时间大于下一个派单的开始时间
//                if ($item2['end_date'] > $dispathOrder['go_date']){
//                    unset($dispatchProceedOrder[$index2]);
//                    continue;
//                }
//                //根据用户id查找司机的用户名
//                $processDriverUserInfo = Db::name('admin_user')->where('id',$item2['driver_user_id'])->find();
//                if ($processDriverUserInfo){
//                    $dispatchProceedOrder[$index2]['realname'] = $processDriverUserInfo['realname'];
//                    $dispatchProceedOrder[$index2]['account'] = $processDriverUserInfo['account'];
//                }else{
//                    $dispatchProceedOrder[$index2]['realname'] = '该司机的用户信息已被删除';
//                }
//                //查找当前的司机信息
//                $driverprocessData = Db::name('driver')->alias('d')
//                    ->join('tp_admin_user u','u.id=d.user_id','left')
//                    ->where($map)
//                    ->where('user_id',$item2['driver_user_id'])
//                    ->order('d.id','desc')
//                    ->field('car_brand,car_model,car_brand_id,car_model_id,arctic_id,user_id,seats,car_type,driver_rank_id,inservice,tag,nationality')->find();
//                if ($driverprocessData) {
//                    $dispatchProceedOrder[$index2]['seats'] = $driverprocessData['seats'];
//                    $dispatchProceedOrder[$index2]['car_type'] = $driverprocessData['car_type'];
//                    $dispatchProceedOrder[$index2]['car_brand_id'] = $driverprocessData['car_brand_id'];
//                    $dispatchProceedOrder[$index2]['car_model_id'] = $driverprocessData['car_model_id'];
//                    $dispatchProceedOrder[$index2]['driver_rank_id'] = $driverprocessData['driver_rank_id'];
//                    $dispatchProceedOrder[$index2]['inservice'] = $driverprocessData['inservice'];
//                    $dispatchProceedOrder[$index2]['tag'] = $driverprocessData['tag'];
//                    $dispatchProceedOrder[$index2]['nationality'] = $driverprocessData['nationality'];
//                }else{
//                    unset($dispatchProceedOrder[$index2]);
//                    continue;
//                }
//                //查找该司机的等级
//                $driverRank = Db::name('driver_rank')->where('id',$driverprocessData['driver_rank_id'])->find();
//                if ($driverRank){
//                    $dispatchProceedOrder[$index2]['r_name'] = $driverRank['name'];
//                }else{
//                    $dispatchProceedOrder[$index2]['r_name'] = '新手';
//                }
//                //过滤有两个订单的司机：进行中或已派单
//                $sendCount = Db::name('dispatch_traveler_group')->where('driver_user_id',$item2['driver_user_id'])
//                    ->where('dispatch_group_status','in','sendorders,proceed')
//                    ->count();
//                if ($sendCount >= 2){
//                    unset($dispatchProceedOrder[$index2]);
//                }
//            }
//            $map_tags['isdelete']=0;
//            $map_tags['status']=1;
//            $driver_tags=Db::name('driver_tag')
//                ->where($map_tags)
//                ->select();
//            //民族
//            $nation = [
//                ['id'=>1,'nationality'=>'阿昌族'],
//                ['id'=>2,'nationality'=>'鄂温克族'],
//                ['id'=>3,'nationality'=>'傈僳族'],
//                ['id'=>4,'nationality'=>'水族'],
//                ['id'=>5,'nationality'=>'白族'],
//                ['id'=>6,'nationality'=>'高山族'],
//                ['id'=>7,'nationality'=>'珞巴族'],
//                ['id'=>8,'nationality'=>'塔吉克族'],
//                ['id'=>9,'nationality'=>'保安族'],
//                ['id'=>10,'nationality'=>'仡佬族'],
//                ['id'=>11,'nationality'=>'满族'],
//                ['id'=>12,'nationality'=>'塔塔尔族'],
//                ['id'=>13,'nationality'=>'布朗族'],
//                ['id'=>14,'nationality'=>'哈尼族'],
//                ['id'=>15,'nationality'=>'毛南族'],
//                ['id'=>16,'nationality'=>'土家族'],
//                ['id'=>17,'nationality'=>'布依族'],
//                ['id'=>18,'nationality'=>'哈萨克族'],
//                ['id'=>19,'nationality'=>'门巴族'],
//                ['id'=>20,'nationality'=>'土族'],
//                ['id'=>21,'nationality'=>'朝鲜族'],
//                ['id'=>22,'nationality'=>'汉族'],
//                ['id'=>23,'nationality'=>'蒙古族'],
//                ['id'=>24,'nationality'=>'佤族'],
//                ['id'=>25,'nationality'=>'达斡尔族'],
//                ['id'=>26,'nationality'=>'赫哲族'],
//                ['id'=>27,'nationality'=>'苗族'],
//                ['id'=>28,'nationality'=>'维吾尔族'],
//                ['id'=>29,'nationality'=>'傣族'],
//                ['id'=>30,'nationality'=>'回族'],
//                ['id'=>31,'nationality'=>'仫佬族'],
//                ['id'=>32,'nationality'=>'乌孜别克族'],
//                ['id'=>33,'nationality'=>'德昂族'],
//                ['id'=>34,'nationality'=>'基诺族'],
//                ['id'=>35,'nationality'=>'纳西族'],
//                ['id'=>36,'nationality'=>'锡伯族'],
//                ['id'=>37,'nationality'=>'东乡族'],
//                ['id'=>38,'nationality'=>'京族'],
//                ['id'=>39,'nationality'=>'怒族'],
//                ['id'=>40,'nationality'=>'瑶族'],
//                ['id'=>41,'nationality'=>'侗族'],
//                ['id'=>42,'nationality'=>'景颇族'],
//                ['id'=>43,'nationality'=>'普米族'],
//                ['id'=>44,'nationality'=>'彝族'],
//                ['id'=>45,'nationality'=>'独龙族'],
//                ['id'=>46,'nationality'=>'柯尔克孜族'],
//                ['id'=>47,'nationality'=>'羌族'],
//                ['id'=>48,'nationality'=>'裕固族'],
//                ['id'=>49,'nationality'=>'俄罗斯族'],
//                ['id'=>50,'nationality'=>'拉祜族'],
//                ['id'=>51,'nationality'=>'撒拉族'],
//                ['id'=>52,'nationality'=>'藏族'],
//                ['id'=>53,'nationality'=>'鄂伦春族'],
//                ['id'=>54,'nationality'=>'黎族'],
//                ['id'=>55,'nationality'=>'畲族'],
//                ['id'=>56,'nationality'=>'壮族'],
//            ];
//            $this->view->assign('nation',$nation);
//            $this->view->assign('driver_tags',$driver_tags);
//            $ranks=Db::name('driver_rank')->select();
//            $this->view->assign('ranks',$ranks);
//            $this->view->assign("driver_users",$driver);
//            $this->view->assign("drivers_in_service",$dispatchProceedOrder);
//            $this->view->assign("drivers_in_send",$dispatchSendOrder);
//            $this->view->assign('vo',$dispathOrder);
//            $this->view->assign('group_id',$group_id);
//            return $this->view->fetch();
//        }
//        //判断订单是否异常
//        $group_order_ids=Db::name('dispatch_traveler')
//
//            ->where('group_id',$group_id)
//            ->column("oid");
//        $exceptional_orders= Db::name('exceptional_order')->where('oid','in',$group_order_ids)->where('solve',false)->find();
//        if($exceptional_orders){
//            return ajax_return_error("订单id为{$exceptional_orders['oid']}的订单存在异常状态");
//        }
//        $dispatch_traveler_group=Db::name('dispatch_traveler_group')->where('id',$group_id)->find();
//
//        if (!input('driver_user_id')){
//            return ajax_return_adv_error('没有选择司机');
//        }
//        //判断司机是否已经在服务
//        $driver=Db::name("driver")->where('user_id',$input['driver_user_id'])->find();
//        if($driver['inservice']){
//            //查找司机的订单
//            //派单或者进行中
//            $driverInfo = Db::name('dispatch_traveler_group')
//                ->where('driver_user_id',$input['driver_user_id'])
//                ->order('id','desc')->select();//找该司机最后的分配订单
//            foreach ($driverInfo as $dik=>$div){
//                if ($div['dispatch_group_status']=='undistributed' ||$div['dispatch_group_status']=='accounts' || $div['dispatch_group_status']=='achieve'){
//                    unset($driverInfo[$dik]);
//                }
//            }
//            $driverInfo  = array_values($driverInfo);
//            $count = count($driverInfo);//统计当前司机有几个单
//            if ($count >= 2){
//                return ajax_return_error("用户id为{$input['driver_user_id']}的司机已经分配2个单");
//            }
//            //寻找该司机的前一单
//            $driver_final_order = $driverInfo[0];
//            if (empty($driver_final_order['end_date'])){
//                return ajax_return_error("用户id为{$input['driver_user_id']}的司机的id为{$driver_final_order['id']}的结束日期没有,不能比较派单");
//            }
//            //寻找该分组的
//            $undistributed = Db::name('dispatch_traveler_group')
//                ->where('id',$group_id)->where('dispatch_group_status','undistributed')->find();
//            if ($undistributed['go_date']<=$driver_final_order['end_date']){
//                return ajax_return_error("用户id为{$input['driver_user_id']}的司机不能派单,原因是上一个订单的结束时间与与本次订单的开始时间有冲突");
//            }
//        }
//        if($dispatch_traveler_group['dispatch_group_status']=='undistributed'||!$dispatch_traveler_group['dispatch_group_status']) {
//            $update=input();
//            $update['dispatch_group_status']='sendorders';
//            $update['driver_confirm']=false;
//            $update['isreject']=false;
//            $update['dispatch_time']=NOW_TIME;
//            Db::name('dispatch_traveler_group')->where('id',$group_id)->update($update);
//            Db::name("driver")->where('user_id',$input['driver_user_id'])->update(array('inservice'=>1));
//            if ($update['driver_user_id']) {
//                $map['user_id'] = $update['driver_user_id'];
//                $map['type'] = "dispatch_traveler_group";
//                $map['dispatch_traveler_group_id'] = $group_id;
//                $title = Db::name('dispatch_traveler_group')->where('id',$group_id)->value('title');
//                logs('20190218ndfghgfh',$map);
//                $re = set_info($dispatch_traveler_group['driver_user_id'], '订单分配', "分配成功，你有新的订单,订单的名称为{$title}", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $group_id));
//                // --------------发送短信给司机-----------------
//                // 查找该司机的手机号码
//                $mobile = Db::name('admin_user')->where('id',$update['driver_user_id'])->value('mobile');
//                if ($mobile){
//                    $ret = send_message($mobile,"分配订单成功,您有新的订单,订单编号为:{$group_id},订单名称为:{$title}");
//                    logs('paidan',$ret);
//                }
//                return ajax_return_adv('操作成功');
//
//            }else{
//
//                return ajax_return_error('未分配司导');
//            }
//        }else{
//            return ajax_return_error('已经分配');
//        }
//    }
}
